萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Content Provider 使用完整教學:存取通訊錄與自訂提供者

Content Provider 核心概念

Content Provider 是 Android 四大組件之一,提供跨應用程式共享資料的標準介面。採用 content:// URI 傳統,封裝資料存取邏輯,支援 CRUD 操作、查詢、批次操作、檔案存取。系統內建 Provider:通訊錄、媒體庫、日曆、通話記錄、簡訊、設定等。

核心 URI 結構

content:///[/]

範例:
content://contacts/people/          # 所有聯絡人
content://contacts/people/123       # ID 為 123 的聯絡人
content://media/external/images/media  # 外部儲存圖片
content://com.example.app.provider/notes/456  # 自訂 Provider

使用現有 Provider:讀取系統通訊錄完整範例

權限宣告

<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- Android 10+ 讀取通訊錄不需額外權限,但建議宣告 -->

查詢所有聯絡人與電話號碼

public class ContactsRepository {
    private final ContentResolver resolver;

    public ContactsRepository(Context context) {
        this.resolver = context.getContentResolver();
    }

    /** 取得所有聯絡人 (含姓名、電話) */
    public List getAllContactsWithPhones() {
        List contacts = new ArrayList<>();
        
        // 1. 查詢原始聯絡人表 (ContactsContract.Contacts)
        // 只查詢有電話號碼的聯絡人
        String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = 1";
        String[] projection = new String[]{
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
            ContactsContract.Contacts.PHOTO_URI,
            ContactsContract.Contacts.STARRED
        };
        
        try (Cursor cursor = resolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                projection,
                selection,
                null,
                ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC")) {
            
            if (cursor == null) return contacts;
            
            int idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY);
            int photoIndex = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI);
            int starredIndex = cursor.getColumnIndex(ContactsContract.Contacts.STARRED);
            
            while (cursor.moveToNext()) {
                String contactId = cursor.getString(idIndex);
                String name = cursor.getString(nameIndex);
                String photoUri = cursor.getString(photoIndex);
                boolean starred = cursor.getInt(starredIndex) == 1;
                
                // 2. 查詢該聯絡人的所有電話號碼
                List phones = getPhoneNumbersForContact(contactId);
                
                // 3. 查詢 Email (可選)
                List emails = getEmailsForContact(contactId);
                
                contacts.add(new Contact(contactId, name, photoUri, starred, phones, emails));
            }
        }
        return contacts;
    }

    private List getPhoneNumbersForContact(String contactId) {
        List phones = new ArrayList<>();
        String selection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
        String[] args = new String[]{contactId};
        String[] projection = new String[]{
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.TYPE,
            ContactsContract.CommonDataKinds.Phone.LABEL,
            ContactsContract.CommonDataKinds.Phone.IS_PRIMARY
        };
        
        try (Cursor cursor = resolver.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, selection, args, null)) {
            
            if (cursor == null) return phones;
            
            int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            int typeIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
            int labelIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL);
            int primaryIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY);
            
            while (cursor.moveToNext()) {
                String number = cursor.getString(numberIndex);
                int type = cursor.getInt(typeIndex);
                String label = cursor.getString(labelIndex);
                boolean isPrimary = cursor.getInt(primaryIndex) == 1;
                phones.add(new PhoneNumber(number, type, label, isPrimary));
            }
        }
        return phones;
    }

    private List getEmailsForContact(String contactId) {
        List emails = new ArrayList<>();
        String selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?";
        String[] args = new String[]{contactId};
        
        try (Cursor cursor = resolver.query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null, selection, args, null)) {
            
            if (cursor == null) return emails;
            
            int addressIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
            int typeIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE);
            int labelIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL);
            
            while (cursor.moveToNext()) {
                String address = cursor.getString(addressIndex);
                int type = cursor.getInt(typeIndex);
                String label = cursor.getString(labelIndex);
                emails.add(new EmailAddress(address, type, label));
            }
        }
        return emails;
    }

    /** 資料模型 */
    public static class Contact {
        public final String id;
        public final String name;
        public final String photoUri;
        public final boolean starred;
        public final List phones;
        public final List emails;
        
        public Contact(String id, String name, String photoUri, boolean starred,
                       List phones, List emails) {
            this.id = id; this.name = name; this.photoUri = photoUri;
            this.starred = starred; this.phones = phones; this.emails = emails;
        }
    }
    
    public static class PhoneNumber {
        public final String number;
        public final int type; // TYPE_HOME, TYPE_MOBILE, TYPE_WORK, TYPE_CUSTOM...
        public final String customLabel;
        public final boolean isPrimary;
        public PhoneNumber(String number, int type, String customLabel, boolean isPrimary) {
            this.number = number; this.type = type; this.customLabel = customLabel; this.isPrimary = isPrimary;
        }
        @Override public String toString() { return number + " (" + getTypeLabel(type, customLabel) + ")"; }
        private String getTypeLabel(int type, String customLabel) {
            switch (type) {
                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME: return "住家";
                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: return "行動";
                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK: return "公司";
                case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM: return customLabel;
                default: return "其他";
            }
        }
    }
    
    public static class EmailAddress {
        public final String address;
        public final int type;
        public final String customLabel;
        public EmailAddress(String address, int type, String customLabel) {
            this.address = address; this.type = type; this.customLabel = customLabel;
        }
    }
}

插入/更新/刪除聯絡人 (需 WRITE_CONTACTS)

public class ContactsManager {
    private final ContentResolver resolver;

    public ContactsManager(Context context) {
        this.resolver = context.getContentResolver();
    }

    /** 新增聯絡人 */
    public Uri addContact(String name, List phones, List emails) {
        ArrayList ops = new ArrayList<>();
        
        // 1. 插入原始聯絡人 (RawContact)
        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) // 本地聯絡人
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
            .build());
        
        // 2. 插入姓名 (Data 表,關聯 raw_contact_id 為上一步結果)
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
            .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // 參考第 0 步驟結果
            .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
            .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
            .build());
        
        // 3. 批次插入電話
        for (PhoneNumber phone : phones) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone.number)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phone.type)
                .withValue(ContactsContract.CommonDataKinds.Phone.LABEL, phone.customLabel)
                .withValue(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY, phone.isPrimary ? 1 : 0)
                .build());
        }
        
        // 4. 批次插入 Email
        for (EmailAddress email : emails) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email.address)
                .withValue(ContactsContract.CommonDataKinds.Email.TYPE, email.type)
                .withValue(ContactsContract.CommonDataKinds.Email.LABEL, email.customLabel)
                .build());
        }
        
        try {
            ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);
            return results[0].uri; // 回傳 RawContact URI
        } catch (Exception e) {
            Log.e("ContactsManager", "Add contact failed", e);
            return null;
        }
    }
}

建立自訂 Content Provider

1. 定義契約類別

public final class NotesContract {
    public static final String AUTHORITY = "com.example.notes.provider";
    public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY);
    
    public static final String PATH_NOTES = "notes";
    public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI, PATH_NOTES);
    
    // MIME 類型
    public static final String CONTENT_TYPE_DIR = "vnd.android.cursor.dir/vnd.example.notes";
    public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.example.notes";
    
    public static class Columns implements BaseColumns {
        public static final String TITLE = "title";
        public static final String CONTENT = "content";
        public static final String CREATED_AT = "created_at";
        public static final String UPDATED_AT = "updated_at";
        public static final String COLOR = "color";
        public static final String IS_PINNED = "is_pinned";
    }
    
    // 建立帶 ID 的 URI
    public static Uri buildNoteUri(long id) {
        return ContentUris.withAppendedId(CONTENT_URI, id);
    }
    
    // 從 URI 取得 ID
    public static long getNoteId(Uri uri) {
        return ContentUris.parseId(uri);
    }
}

2. 實作 ContentProvider 子類

public class NotesProvider extends ContentProvider {
    private static final String TAG = "NotesProvider";
    private NotesDbHelper dbHelper;
    
    // URI Matcher 程式碼
    private static final int NOTES = 100;
    private static final int NOTE_ID = 101;
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    static {
        uriMatcher.addURI(NotesContract.AUTHORITY, NotesContract.PATH_NOTES, NOTES);
        uriMatcher.addURI(NotesContract.AUTHORITY, NotesContract.PATH_NOTES + "/#", NOTE_ID);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new NotesDbHelper(getContext());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, 
                        @Nullable String selection, @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        int match = uriMatcher.match(uri);
        
        Cursor cursor;
        switch (match) {
            case NOTES:
                cursor = db.query(NotesDbHelper.TABLE_NOTES, projection, selection, selectionArgs,
                    null, null, sortOrder != null ? sortOrder : NotesContract.Columns.CREATED_AT + " DESC");
                break;
            case NOTE_ID:
                String id = uri.getLastPathSegment();
                cursor = db.query(NotesDbHelper.TABLE_NOTES, projection,
                    NotesContract.Columns._ID + " = ?", new String[]{id}, null, null, null);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        // 關鍵:設定通知 URI,資料變更時自動通知 Cursor/Loader
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (uriMatcher.match(uri)) {
            case NOTES: return NotesContract.CONTENT_TYPE_DIR;
            case NOTE_ID: return NotesContract.CONTENT_TYPE_ITEM;
            default: throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        if (uriMatcher.match(uri) != NOTES) {
            throw new IllegalArgumentException("Insert only supports directory URI");
        }
        
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long id = db.insert(NotesDbHelper.TABLE_NOTES, null, values);
        if (id == -1) throw new SQLException("Failed to insert: " + uri);
        
        // 通知資料變更
        getContext().getContentResolver().notifyChange(uri, null);
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int match = uriMatcher.match(uri);
        int count;
        
        switch (match) {
            case NOTES:
                count = db.delete(NotesDbHelper.TABLE_NOTES, selection, selectionArgs);
                break;
            case NOTE_ID:
                String id = uri.getLastPathSegment();
                count = db.delete(NotesDbHelper.TABLE_NOTES, 
                    NotesContract.Columns._ID + " = ?", new String[]{id});
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        if (count > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, 
                      @Nullable String selection, @Nullable String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int match = uriMatcher.match(uri);
        int count;
        
        switch (match) {
            case NOTES:
                count = db.update(NotesDbHelper.TABLE_NOTES, values, selection, selectionArgs);
                break;
            case NOTE_ID:
                String id = uri.getLastPathSegment();
                count = db.update(NotesDbHelper.TABLE_NOTES, values,
                    NotesContract.Columns._ID + " = ?", new String[]{id});
                break;
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
        
        if (count > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] valuesArray) {
        if (uriMatcher.match(uri) != NOTES) return super.bulkInsert(uri, valuesArray);
        
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        int count = 0;
        try {
            for (ContentValues values : valuesArray) {
                long id = db.insert(NotesDbHelper.TABLE_NOTES, null, values);
                if (id != -1) count++;
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        
        if (count > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }
    
    // 可選:支援檔案存取 (openFile)
    @Nullable
    @Override
    public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
        // 實作檔案存取邏輯
        return super.openFile(uri, mode);
    }
}

3. Manifest 宣告 Provider

<provider
    android:name=".NotesProvider"
    android:authorities="com.example.notes.provider"
    android:exported="false"          <!-- 預設 false,跨應用需 true -->
    android:grantUriPermissions="true" <!-- 允許臨時授權 -->
    android:readPermission="com.example.perm.READ_NOTES"
    android:writePermission="com.example.perm.WRITE_NOTES"
    android:multiprocess="true" />     <!-- 多進程支援 -->

4. 客戶端使用自訂 Provider

public class NotesClient {
    private final ContentResolver resolver;

    public NotesClient(Context context) {
        this.resolver = context.getContentResolver();
    }

    public Cursor queryAllNotes() {
        return resolver.query(NotesContract.CONTENT_URI, null, null, null, 
            NotesContract.Columns.CREATED_AT + " DESC");
    }

    public Uri insertNote(String title, String content, int color) {
        ContentValues values = new ContentValues();
        values.put(NotesContract.Columns.TITLE, title);
        values.put(NotesContract.Columns.CONTENT, content);
        values.put(NotesContract.Columns.COLOR, color);
        values.put(NotesContract.Columns.CREATED_AT, System.currentTimeMillis());
        return resolver.insert(NotesContract.CONTENT_URI, values);
    }

    public int updateNote(long id, ContentValues values) {
        values.put(NotesContract.Columns.UPDATED_AT, System.currentTimeMillis());
        Uri uri = NotesContract.buildNoteUri(id);
        return resolver.update(uri, values, null, null);
    }

    public int deleteNote(long id) {
        Uri uri = NotesContract.buildNoteUri(id);
        return resolver.delete(uri, null, null);
    }
}

現代替代方案:Room + ContentProvider (可選)

Room 2.1+ 支援 @ContentProvider 註解自動產生 Provider,但通常不建議為了跨應用共享而暴露 Room DB。較佳架構:

  • 應用內部:Room + Repository + Flow/LiveData
  • 跨應用共享:專用 ContentProvider 包裝 Room,控制權限、資料格式、遷移

總結

Content Provider 是 Android 跨應用資料共享的標準機制。使用系統 Provider (通訊錄、媒體庫) 需正確宣告權限、使用 ContentResolver 操作、善用 applyBatch 批次寫入。自訂 Provider 需實作 CRUD、getType、UriMatcher、notifyChange 通知機制。現代開發中,應用內部資料存取優先用 Room,跨應用共享才暴露 Provider。

copyright © 萬盛學電腦網 all rights reserved