Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入解析 Android 自定義 ContentProvider

編輯:關於 Android 開發

在 Android 開發中,數據共享一直是一個繞不開的話題。本文將從 ContentProvider 的基本概念出發,帶你理解它的設計思路、URI 結構,並一步步動手實現一個可用的自定義 ContentProvider。

為什麼需要 ContentProvider

想像一個常見場景:A 應用保存了一批數據,而 B 應用也需要讀取這批數據。要如何安全、規範地把數據共享出去?直接把文件丟到 SD 卡、或者繞道網絡,都不是理想方案。Android 給出的標準答案是 ContentProvider。

系統自帶的相冊、聯繫人等應用,本身就是 Google 為 Android 撰寫的 App,它們都通過 ContentProvider 對外暴露數據,並提供一套統一的 API 供我們調用。ContentProvider 的核心思想,是把「讀取」與「存儲」都封裝在同一套接口之下,而定位數據的關鍵就是 URI。

ContentProvider 的三大優點

它主要解決了以下問題:

  • 可以讀取系統原生應用的數據,例如聯繫人、通話記錄等。
  • 讓不同 App 之間能夠以規範的方式共享數據。
  • 對數據訪問進行封裝,為存儲與獲取提供一致的 API。

如果想讀取系統應用數據,可以直接參考 android.provider 包下已有的各類 Provider。

URI 的結構

ContentProvider 通過 URI 來唯一標識一條數據或一批數據。以 content://com.camnter.content.provider/message/6 為例:

  • content://:Scheme,固定寫法。
  • com.camnter.content.provider:Authority(主機名),是這個 ContentProvider 的唯一標識。
  • message:Table,即表名。
  • 6:Id,具體記錄的編號。

幾個對照的例子:

  • content://com.camnter.content.provider/message:操作 message 表的所有記錄。
  • content://com.camnter.content.provider/message/6:操作 message 表中 Id = 6 的記錄。
  • content://com.camnter.content.provider/message/6/content:操作 Id = 6 這條記錄的 content 字段。

Google 提供的 URI 工具類

直接使用字符串拼接 URI 容易出錯,因此官方提供了兩個常用工具類。

UriMatcher 用於 URI 匹配:

  • addURI(String authority, String path, int code):把一條 URI 規則加入內部列表,並關聯一個整數 code。
  • match(Uri uri):傳入待匹配的 URI,返回註冊時關聯的 code,未命中則返回 -1。

ContentUris 用於解析與拼接 Id:

  • parseId(Uri contentUri):從 URI 中解析出 Id。
  • withAppendedId(Uri contentUri, long id):在 URI 末尾追加 Id。
  • appendId(Uri.Builder builder, long id):向 Builder 追加 Id。

UriMatcher 的匹配原理

UriMatcher 的本質是一棵前綴樹。註冊時,它會把 authority 和 path 按 / 拆分,逐段建立節點;匹配時,再沿著同樣的路徑逐段查找。其中 # 匹配純數字,* 匹配任意文本,其餘按精確字符串匹配。這種設計讓我們不必寫大量 if-else 就能判斷 URI 類型。

註冊示例:

static {
    sURIMatcher.addURI("contacts", "people", PEOPLE);
    sURIMatcher.addURI("contacts", "people/#", PEOPLE_ID);
    sURIMatcher.addURI("contacts", "phones/filter/*", PHONES_FILTER);
}

使用時只需一次 match,再根據返回的 code 分發邏輯:

public String getType(Uri url) {
    switch (sURIMatcher.match(url)) {
        case PEOPLE:     return "vnd.android.cursor.dir/person";
        case PEOPLE_ID:  return "vnd.android.cursor.item/person";
        default:         return null;
    }
}

動手實現自定義 ContentProvider

自定義 ContentProvider 需要繼承 ContentProvider 並實現六個核心方法:onCreate、query、getType、insert、delete、update。我們先約定兩種 MIME 類型:單條數據以 vnd.android.cursor.item/ 開頭,數據集以 vnd.android.cursor.dir/ 開頭。

第一步:準備數據庫幫助類 MessageSQLiteHelper

public class MessageSQLiteHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "message.db";
    private static final int VERSION = 1;
    public static final String TB_MESSAGE = "tb_message";
    public static final String TB_MESSAGE_SQL =
            "CREATE TABLE IF NOT EXISTS " + TB_MESSAGE +
            "(_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, content text)";

    private static MessageSQLiteHelper ourInstance;

    public static MessageSQLiteHelper getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new MessageSQLiteHelper(context);
        }
        return ourInstance;
    }

    private MessageSQLiteHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TB_MESSAGE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 依實際需求處理升級邏輯
    }
}

第二步:實現 MessageContentProvider

關鍵在於用 UriMatcher 區分「操作整表」與「操作單條記錄」兩種情況,並在增刪改之後調用 notifyChange 通知观察者。

public class MessageContentProvider extends ContentProvider {
    private static final String AUTHORITY = "com.camnter.content.provider";
    public static final Uri MESSAGE_URI =
            Uri.parse("content://" + AUTHORITY + "/message");

    private static final String SINGLE = "vnd.android.cursor.item/message";
    private static final String MULTIPLE = "vnd.android.cursor.dir/message";

    private static final int MESSAGE = 6;   // 帶 id
    public static final int MESSAGES = 7;   // 整表

    private MessageSQLiteHelper helper;
    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        MATCHER.addURI(AUTHORITY, "message", MESSAGES);
        MATCHER.addURI(AUTHORITY, "message/#", MESSAGE);
    }

    @Override
    public boolean onCreate() {
        helper = MessageSQLiteHelper.getInstance(getContext());
        return true;
    }

    @Override
    public String getType(Uri uri) {
        switch (MATCHER.match(uri)) {
            case MESSAGE:  return SINGLE;
            case MESSAGES: return MULTIPLE;
            default:       return null;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        long id = db.insert(MessageSQLiteHelper.TB_MESSAGE, "content", values);
        getContext().getContentResolver().notifyChange(uri, null);
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int count;
        switch (MATCHER.match(uri)) {
            case MESSAGES:
                count = db.delete(MessageSQLiteHelper.TB_MESSAGE, selection, selectionArgs);
                break;
            case MESSAGE:
                String where = "_id=" + ContentUris.parseId(uri);
                count = db.delete(MessageSQLiteHelper.TB_MESSAGE, where, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int count;
        switch (MATCHER.match(uri)) {
            case MESSAGES:
                count = db.update(MessageSQLiteHelper.TB_MESSAGE, values, selection, selectionArgs);
                break;
            case MESSAGE:
                String where = "_id=" + ContentUris.parseId(uri);
                count = db.update(MessageSQLiteHelper.TB_MESSAGE, values, where, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor;
        switch (MATCHER.match(uri)) {
            case MESSAGES:
                cursor = db.query(MessageSQLiteHelper.TB_MESSAGE, projection,
                        selection, selectionArgs, null, null, sortOrder);
                break;
            case MESSAGE:
                String where = "_id=" + ContentUris.parseId(uri);
                cursor = db.query(MessageSQLiteHelper.TB_MESSAGE, projection,
                        where, selectionArgs, null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }
}

第三步:在清單文件中註冊

記得在 AndroidManifest.xml 中聲明這個 Provider,並設置 android:exported 控制是否允許外部訪問:

<provider
    android:name=".MessageContentProvider"
    android:authorities="com.camnter.content.provider"
    android:exported="true" />

調用方如何使用

外部應用拿到 ContentResolver 後,就能像操作數據庫一樣進行增刪改查:

ContentResolver resolver = getContentResolver();
// 插入
ContentValues values = new ContentValues();
values.put("content", "Save you from anything");
resolver.insert(MessageContentProvider.MESSAGE_URI, values);
// 查詢
Cursor c = resolver.query(MessageContentProvider.MESSAGE_URI, null, null, null, null);

還可以通過 registerContentObserver 監聽數據變化,實現界面自動刷新。

小結

ContentProvider 的本質是「基於 URI 的統一數據訪問層」。掌握 URI 結構、UriMatcher 匹配機制,以及六個核心方法的職責,就能寫出一個結構清晰、可對外共享數據的 Provider。實際項目中,官方更推薦使用 Jetpack 的 Room 或 DataStore 等方案來簡化數據層開發,但理解 ContentProvider 的原理,對於讀懂系統 API 與跨進程數據共享仍然非常重要。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved