用途
不同于File, SharedPreferences和DataBase,Content Provider主要用于不同的应用程序间共享数据,允许一个程序安全的访问另一个程序中的数据。
用法
通过Context的getContentResolver()取得该类的实例。然后是和数据库相似的CRUD操作,其中query()方法返回Cursor对象,可以通过moveToNext()将数据逐一读出,然后是cursor.clse()关闭。
// Get the Cursor of all the contacts Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); // Move the cursor to first. Also check whether the cursor is empty or not. if (cursor.moveToFirst()) { // Iterate through the cursor do { // Get the contacts name String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); contacts.add(name); } while (cursor.moveToNext()); } // Close the curosor cursor.close();
自定义内容提供器
如果要实现自己的内容提供器,要继承自ContentProvider,然后去覆盖onCreate, query, insert, update, delete, getType六个方法,这六个方法必须全部重写。