Content Provider相当于数据的接口,通过Content Provider可以将程序内部使用的数据向其他程序公开,这样其他的程序就可以通过Context.getContentResolver方法获得ContentResolver对象,并使用ContentResolver.insert, ContentResolver.delete, ContentResolver.update, ContentResolver.query 4个方法对程序内部的数据进行增,删,改,查操作。
Android系统中内置的应用大多都提供了Content Provider。
读取联系人信息
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
//查询系统中所有的联系人
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//根据cursor创建SimpleCursorAdapter对象
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor,
new String[]{ContactsContract.Contacts.DISPLAY_NAME},
new int[]{R.id.lie});
listView.setAdapter(adapter);
}
}
uri参数的值是一个常量,定义如下:
public static final String AUTHORITY = "com.android.contacts";
public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY);
public static final Uri CONTENT_URI = Uri.withAppendedPath(AUTHORITY_URI,"contacts");
查询系统联系人需要权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
上面只是用了查询,当然也可以增加,修改,删除。
查看收件箱的短信
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
//查询收件箱中电话号以“1”开头的短信
Cursor cursor = getContentResolver().query(Uri.parse("content://sms"), null, "address like ?", new String[]{"1"}, null);
//创建SMSAdapter对象
SMSAdapter smsAdapter = new SMSAdapter(this,cursor);
listView.setAdapter(smsAdapter);
}
}
public class SMSAdapter extends CursorAdapter{
private LayoutInflater layoutInflater;
public SMSAdapter(Context context,Cursor){
super(context,cursor);
//调用LayoutInflater.inflate方法装载布局资源
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View newView(Context context,Cursor cursor,ViewGroup parent){
View view = layoutInflater.inflate(R.layout.item,null);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor){
TextView tvPhoneNumber = (TextView)view.findViewById(R.id.tvPhoneNumber);
TextView tvContent = (TextView)view.findViewById(R.id.tvContent);
//显示电话号
tvPhoneNumber.setText(cursor.getString(cursor.getColumnIndex("address")));
//显示短信内容
tvContent.setText(cursor.getString(cursor.getColumnIndex(body)));
}
}