内容提供者
整体来说内容提供者就相当于别的应用提供了一个数据供你访问,比如访问短信,就是使用的内容提供者
public class readsms extends AppCompatActivity {
private TextView textView;
private Button sms;
String text;
Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
textView.setText(((String)msg.obj));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_readsms);
textView = findViewById(R.id.smstext);
sms = findViewById(R.id.sms);
sms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
read();
}
});
}
public void read()
{
Uri uri=Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(uri, new String[]{"_id", "address", "type", "body", "date"}, null, null, null);
List<smsinfo> smsinfos=new ArrayList<>();
if(cursor!=null && cursor.getCount()>0)
{
while (cursor.moveToNext())
{
int id=cursor.getInt(0);
String address=cursor.getString(1);
int type=cursor.getInt(2);
String body=cursor.getString(3);
long date=cursor.getLong(4);
smsinfo smsinfo=new smsinfo(id,address,type,body,date);
smsinfos.add(smsinfo);
}
cursor.close();
}
text="手机号码"+smsinfos.get(1).getAddress()+"\n";
text="短信内容"+smsinfos.get(1).getBody()+"\n";
Message message=new Message();
message.obj=text;
handler.sendMessage(message);
}
}
不难看出
1.先创建ContentResolver对象,同时指定Uri接口,注意是Uri不是Url
Uri uri=Uri.parse("content://sms/");
ContentResolver resolver = getContentResolver();
短信提供了一个SQLlist数据库
Cursor cursor = resolver.query(uri, new String[]{"_id", "address", "type", "body", "date"}, null, null, null);
因此这样接收但是别忘了,任何东西都要封装为一个对象