編輯:關於 Android 程式設計
Android 提供了五種數據存儲方式:SharedPreferences、網絡存儲、內部文件存儲、外部存儲以及 SQLite。這些方式通常只在單個應用內部實現數據共享。但有時候我們需要訪問其他應用的數據——系統通訊錄、短信、媒體庫都是典型例子。這正是 ContentProvider 要解決的問題。
ContentProvider 可以理解為「內容提供者」,本質上是一層供外部訪問的接口,必要時還能配合權限控制。
每個 Android 應用都運行在獨立進程中,彼此默認隔離,但跨應用的數據共享又是現實需求。ContentProvider 的價值在於統一了數據訪問方式。總結起來有幾點:
它為存儲和獲取數據提供了統一接口;
它對底層存儲細節做了封裝,調用方無需關心數據究竟存在哪裡;
它以表格形式組織數據,概念上與數據庫表一致;
它讓不同應用之間的數據共享成為可能;
Android 本身也為音頻、視頻、圖片、通訊錄等常見數據提供了默認的 ContentProvider。
訪問 ContentProvider 的入口是 Uri(Universal Resource Identifier,通用資源標識符)——注意不是 URL。以讀取通訊錄為例:
content://contacts/people
拆开来看,它由三部分組成:
content:// —— 固定前綴,代表這是一個 ContentProvider 類型的資源。
contacts —— 主機名,也叫 Authority,用於唯一標識某個 ContentProvider。外部調用方依此定位到目標。這個字段的唯一性至關重要,實務上通常直接用包名。
people —— 路徑(path),表示要操作的具體數據集合,如何劃分取決於業務設計。
要當內容提供者,首先得有數據。先建一個 SQLiteOpenHelper:
public class SqlDBConnection extends SQLiteOpenHelper {
private static final String DbName = "Book.db";
private static int version = 1;
public SqlDBConnection(Context context) {
super(context, DbName, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sqlString = "create table Book (id integer primary key autoincrement,"
+ "Name nvarchar(200), Title nvarchar(200))";
db.execSQL(sqlString);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
接著用 AndroidTestCase 灌入一些測試數據,這一步在後續驗證時很有用:
public class BookCase extends AndroidTestCase {
public void Intial() {
SqlDBConnection dbConnection = new SqlDBConnection(getContext());
SQLiteDatabase sqlDataBase = dbConnection.getWritableDatabase();
long row = 0;
for (int i = 0; i < 5; i++) {
ContentValues values = new ContentValues();
values.put("Name", "書籍" + i);
values.put("Title", "標題" + i);
row = sqlDataBase.insert("Book", null, values);
Log.i("BookCase", "插入成功:" + row);
}
}
}
數據準備好之後,就可以編寫自己的 ContentProvider 並重寫 insert、update、delete、query 等方法,根據傳入的 Uri 路徑判斷具體操作。
關鍵的一步是在 AndroidManifest.xml 中註冊,並指定唯一的 authorities。實務上直接沿用包名最省事:
<provider
android:name="com.example.googlecontentprovider.MyContentProvider"
android:authorities="com.example.googlecontentprovider.MyContentProvider" />
這裡 android:name 指向 Provider 類本身,android:authorities 則是外部調用方拼接 Uri 時使用的主機名,兩者概念不同但取值相同,容易混淆。
方法寫在自己應用中調用屬正常,讓另一個應用來調用才叫接口。ContentResolver 就是外部訪問的統一入口。
先確認一下初始化後的數據:

新建一個測試項目 BookCase,先來插入數據。這裡的 Uri 主機名就是上面配置的 authorities,路徑 book/insert 與 Provider 內部判斷分支的常量對應:
public void bookInsert() {
Uri uri = Uri.parse("content://com.example.googlecontentprovider.MyContentProvider"
+ "/book/insert");
ContentResolver resolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put("Name", "書籍5");
values.put("Title", "標題5");
uri = resolver.insert(uri, values);
Log.i("BookCase", "Uri" + uri);
long id = ContentUris.parseId(uri);
Log.i("BookCase", "測試成功" + id);
}

更新剛才插入的記錄,同樣拼接 Uri 並取得 ContentResolver:
public void bookUpdate() {
Uri uri = Uri.parse("content://com.example.googlecontentprovider.MyContentProvider"
+ "/book/update");
ContentResolver resolver = getContext().getContentResolver();
ContentValues values = new ContentValues();
values.put("Name", "修改");
int count = resolver.update(uri, values, " id=?", new String[]{"10"});
Log.i("BookCase", "更新了" + count + "行");
}

刪除數據:
public void bookDelete() {
Uri uri = Uri.parse("content://com.example.googlecontentprovider.MyContentProvider"
+ "/book/delete");
ContentResolver resolver = getContext().getContentResolver();
String where = " id=?";
String[] argString = {"10"};
int count = resolver.delete(uri, where, argString);
Log.i("BookCase", "刪除了" + count + "行");
}

查詢全部數據:
public void bookQuery() {
Uri uri = Uri.parse("content://com.example.googlecontentprovider.MyContentProvider"
+ "/book/query");
ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = resolver.query(uri,
new String[]{"id", "Name", "Title"}, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String nameString = cursor.getString(cursor.getColumnIndex("Name"));
String titleString = cursor.getString(cursor.getColumnIndex("Title"));
Log.i("BookCase", id + "---" + nameString + "---" + titleString);
}
}
}
Log 輸出:

查詢單條記錄時,用 ContentUris.withAppendedId() 把 id 附加到 Uri 末尾即可:
public void bookQuerySingle() {
Uri uri = Uri.parse("content://com.example.googlecontentprovider.MyContentProvider"
+ "/book/query");
ContentResolver resolver = getContext().getContentResolver();
uri = ContentUris.withAppendedId(uri, 1);
Cursor cursor = resolver.query(uri,
new String[]{"id", "Name", "Title"}, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("Id"));
String nameString = cursor.getString(cursor.getColumnIndex("Name"));
String titleString = cursor.getString(cursor.getColumnIndex("Title"));
Log.i("BookCase", id + "---" + nameString + "---" + titleString);
}
}
}

把整個流程串起來看,ContentProvider 的調用模式非常一致:拼 Uri → 取 ContentResolver → 調對應方法。的差異只在於路徑部分,這也體現了它「以 Uri 為唯一入口」的設計。
幾個實戰中值得注意的地方:
一是 authorities 全局唯一。若兩個應用聲明了相同的 authorities,安裝時後者會失敗,這也是為什麼推薦直接用包名。
二是 Cursor 用完記得關閉。上文示例為了簡潔省略了 close(),實際代碼中應在 finally 中釋放,或使用 try-with-resources,否則容易觸發 Cursor 洩染警告甚至內存洩漏。
三是 查詢完畢後記得判空並處理空 Cursor,避免 getCount() 為 0 時仍去遍歷。
四是 對外暴露數據時考慮權限控制。在 Manifest 中透過 android:readPermission 與 android:writePermission 聲明自定義權限,能避免任意應用隨意讀寫你的數據。
Android 搜索框即時顯示清空按鈕
在搜索相關頁面中,加入一鍵清空輸入內容的功能,可以提升使用者體驗,讓刪除文字更直覺。常見做法是把 EditText 與一個清空 ImageView 放在同一個相對佈局中。
Android 資料儲存筆記(二):用 XML 備份簡訊的完整實作
實務開發中常會遇到需要儲存或備份結構較複雜的資料,例如整批簡訊。這類資料的特徵是筆數多、每筆還帶有多個欄位,用 SharedPreferences 或純文字檔去存,效率與
手把手教你搞懂 Android 反編譯
我們知道,Android 程序打包後會生成一個 APK 文件,這個文件可以直接安裝到任何 Android 手機上,因此,反編譯就是對這個 APK 進行逆向還原。Andro
給 C# 開發者的 Android 筆記:按鈕點擊事件的四種寫法
經過前兩篇鋪墊,這次做個簡單的熱身:把按鈕點擊的四種常見寫法一次跑過。對 C# 開發者而言,這個題目特別有意思,因為它清楚展示了「事件」這個概念在兩種語言裡的不同落地方式