android中對數(shù)據(jù)操作包含有:
file, sqlite3, Preferences, ContectResolver與ContentProvider前三種數(shù)據(jù)操作方式都只是針對本應(yīng)用內(nèi)數(shù)據(jù),程序不能通過這三種方法去操作別的應(yīng)用內(nèi)的數(shù)據(jù)。
android中提供ContectResolver與ContentProvider來操作別的應(yīng)用程序的數(shù)據(jù)。
一、 使用方式
一個應(yīng)用實現(xiàn)ContentProvider來提供內(nèi)容給別的應(yīng)用來操作,
一個應(yīng)用通過ContentResolver來操作別的應(yīng)用數(shù)據(jù),當(dāng)然在自己的應(yīng)用中也可以。
1. ContentResolver的獲取
通過Context類:
以上操作實際是通過Uri來匹配ContentProvider, 再由ContentProvider來進(jìn)行具體操作的。
操作的參數(shù)和操作sqlite各函數(shù)的參數(shù)意義是一樣的。
二、實現(xiàn)ContentProvider提供給外界訪問
調(diào)用者ContentResoler是通過一個Uri來找到相應(yīng)的ContentProvider的來進(jìn)行實際操作。
1. Uri概念
一個Uri的樣子如:
如電話記錄:
a.根據(jù)scheme不同調(diào)用不程序來處理, 常用的:content, android_resource, file, http等
b.authorities是provider定義的,在AndroidManifest.xml中定義
c.path和id就好理解的。
2. Uri定義
創(chuàng)建自己的Uri, 如:
一般數(shù)據(jù)中都有dir和item兩種(當(dāng)然可定義多個)。為ContentProvider創(chuàng)建息的UriMatcher并添加這兩者:
contentProvider要根據(jù)傳入uri判斷是dir還是item來操作的。
來分步操作.
3. 定義MIME類型,
覆蓋getType方法:主要是根據(jù)uri來返回Provider的MIME類型
getType()為:
4. 實現(xiàn)query, insert, delete, update四個操作。
具體的實現(xiàn)可以用sqlite, file等。并根據(jù)uri分情況操作。
a. query時如果是item加查詢條件id.
where = "_ID=" + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : "";
最后要加上
cursor.setNotificationUri(getContext().getContentResolver(), uri);
b. insert時要求uri只能是dir. 成功之后返回一個加id的uri.
c. update、delete與query差不多。
新聞熱點
疑難解答
圖片精選