Content Provider總結(jié)

Content Provider是什么

組件Content Provider是為了在不同應(yīng)用程序之間進行數(shù)據(jù)交換的的標準API。比如,一個應(yīng)用有一些數(shù)據(jù),它可以允許別的應(yīng)用來訪問這些數(shù)據(jù),那么它可以通過ContentProvider來暴露訪問這些數(shù)據(jù)的接口,當別的應(yīng)用想要訪問這些數(shù)據(jù)時可以通過ContentResolver來操作,包括增刪改查等等。

Content Provider簡單使用

下面是一個簡單的例子,我們可以通過ContentResolver內(nèi)容解析者來訪問系統(tǒng)里通訊錄里面的聯(lián)系人信息。

  1. 新建布局文件 layout_activity_cp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="center"
              android:orientation="vertical">

    <Button
        android:id="@+id/btn_read_contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="讀取聯(lián)系人數(shù)據(jù)"/>
</LinearLayout>
  1. 新建Activity
public class ContentProviderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //設(shè)置布局
        setContentView(R.layout.layout_activity_cp);

        //按鈕點擊事件
        Button btnReadContact = (Button) findViewById(R.id.btn_read_contact);
        btnReadContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Cursor mCursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                        null, null, null, null);

                while (mCursor.moveToNext()) {

                    String name = mCursor.getString(mCursor.getColumnIndex
                            (ContactsContract.Contacts.DISPLAY_NAME));

                    Log.e("---contactname---", name);

                }

            }
        });

    }
}
  1. 清單文件 AndroidManifest.xml里添加讀取聯(lián)系人的權(quán)限,同時別忘了要注冊Activity。
 <uses-permission android:name="android.permission.READ_CONTACTS"/>

這樣,運行后查看輸出結(jié)果如下圖所示:

QinQin---XiaoMing

Content Provider自定義

步驟

  1. SQLite數(shù)據(jù)庫表,用于存儲數(shù)據(jù)。
  2. 創(chuàng)建一個繼承自ContentProvider的子類,在其中完成數(shù)據(jù)操作。
  3. AndroidManifest.xml文件中聲明provider
  4. 外部訪問

用法解析

  1. 創(chuàng)建數(shù)據(jù)庫。這里用SQLite數(shù)據(jù)庫保存數(shù)據(jù)。
1
  1. 新建繼承自ContentProvider的子類,完成基本操作。
2
3
  1. 在清單文件里聲明provider。
3
  1. 數(shù)據(jù)訪問
4
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容