跨程序共享數據

能夠利用getContentResolver()獲取ContentResolver. ContentResolver中提供了一系列方法用於對數據進行CRUD操做.
java

ContentProvider

經過getContentResolver()獲取ContentResolver的實例,ContentResolver中提供了一系列方法用於對數據進行CRUD操做.
其中
1.insert() 用於添加
2.update() 用於更新
3.delete() 用於刪除
4.query() 用於查詢android

內容URI及用法

ContentResolver中的CRUD操做是不接受表名參數的,而是使用一個Uri參數代替。該參數被稱爲內容URI,由兩部分組成:authority和path。
內容URI標準寫法:數據庫

content://com.example.app.provider/table1

須要將內容URI解析成Uri對象才能夠做爲參數傳入安全

Uri uri=Uri.parse("content://com.example.app.provider/table1");

查詢操做

Cursor cursor=getContentResolver().query(uri,projection,selection,selectionArgs,orderBy);

其它操做與之相似,也和SQLite中的操做相像。
markdown

自定義ContentProvider

能夠extends ContentProvider,須要覆蓋父類的6個方法.app

1.public boolean onCreate():初始化ContentProvider時調用,完成對數據庫的建立和升級,返回true則表示ContentProvider初始化成功,返回false表示失敗。注意:只有存在ContentResolver嘗試訪問該程序中的而數據時,ContentProvider纔會初始化
2.public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder):從ContentProvider中查詢數據。使用uri參數來肯定查詢哪一張表,projection用於肯定查詢哪些列,selectionselectionArgs用來約束查詢內容,sordOreder參數用於對結果進行排序,查詢結果放在Cursor中返回。
3.public Uri insert(Uri uri, ContentValues values):向ContentProvider中添加一條數據。
4.public int delete(Uri uri, String selection, String[] selectionArgs):從ContentProvider中刪除數據。
5.public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs):更新數據
6.public String getType(Uri uri):根據傳入的內容URI來返回相對應的MIME類型。ide

一個內容URI對應的MIME字符串由三部分組成:
1.必須以vnd開頭。
2.若是內容URI以路徑結尾,則后街androi.cursor.dir/,若是內容URI以id結尾,則後接android.cursor.item/
3.最後街上vnd.<authority>.<path>spa

安全性保證

由於全部的CRUD操做都必定要匹配到相應的內容URI格式才能進行,因此咱們能夠控制外部程序可以得到的存儲內容。code

相關文章
相關標籤/搜索