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

ContentProvider 完全指南:跨應用資料分享、UriMatcher 與單元測試實作

編輯:關於 Android 程式設計

一、ContentProvider 基本概念

為了讓不同應用之間能安全地交換資料,Android 提供了 ContentProvider。它是跨應用資料交換的標準 API:當一個應用願意把自己的資料對外公開時,就實作一個 ContentProvider;其他應用則透過 ContentResolver 來操作這些被公開的資料。這層間接設計的意義在於——存取權限由 provider 一方掌控,consumer 拿到的只是一個 URI 與一組操作語意,彼此並不互相侵入。

實作 ContentProvider 的步驟:

1)建立一個類別繼承 ContentProvider,並重寫其中的 CRUD 方法。

2)在 AndroidManifest.xml 中註冊 provider。

註冊時需要三個關鍵屬性:

android:name  provider 的實作類別
android:authorities provider 的 URI 授權字串(全域唯一)
android:exported  是否開放給其他應用存取

ContentResolver 如何操作 ContentProvider:

1)呼叫 getContentResolver() 取得 ContentResolver。此方法來自 ContextWrapper,因此 Activity 與 Service 都能使用。

2)呼叫 CRUD 方法,並以 URI 參數指定要操作哪一個 provider。

二、Demo:插入資料並顯示在 ListView

main.xml:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main" >

    <ListView android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout> 

MySQLiteOpenHelper 類別

 package com.app.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    public MySQLiteOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String create_sql =
                "create table tb_test(_id integer primary key autoincrement,name,gender,age)";
        db.execSQL(create_sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
} 

MyContentProvider 類別

 package com.app.dao;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class MyContentProvider extends ContentProvider {

    MySQLiteOpenHelper helper = null;

    @Override
    public int delete(Uri arg0, String arg1, String[] arg2) {
        return 0;
    }

    @Override
    public String getType(Uri arg0) {
        return null;
    }

    @Override
    public Uri insert(Uri arg0, ContentValues values) {
        String insert_sql = "insert into tb_test values(null,'wx','boy',17)";
        helper.getReadableDatabase().execSQL(insert_sql);
        return null;
    }

    @Override
    public boolean onCreate() {
        helper = new MySQLiteOpenHelper(this.getContext(), "test.db3", null, 1);
        return true;
    }

    @Override
    public Cursor query(Uri arg0, String[] arg1, String arg2,
            String[] arg3, String arg4) {
        String query_sql = "select * from tb_test";
        return helper.getReadableDatabase().rawQuery(query_sql, null);
    }

    @Override
    public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
        return 0;
    }
} 

ListView 的列樣式 show.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:id="@+id/gender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="60dp" />
    <TextView android:id="@+id/age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="60dp" />
</LinearLayout> 

Main.java

 package com.app.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class Main extends Activity {

    ContentResolver resolver = null;
    ListView lv = null;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv = (ListView) this.findViewById(R.id.listview);
        resolver = this.getContentResolver();

        String str = "content://com.app.test.db/";
        Uri uri = Uri.parse(str);

        resolver.insert(uri, null);   // 插入一筆
        Cursor cursor = resolver.query(uri, null, null, null, null);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.show,
                cursor,
                new String[] { "name", "gender", "age" },
                new int[] { R.id.name, R.id.gender, R.id.age },
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lv.setAdapter(adapter);
    }
} 

記得在 manifest 中註冊:

 <provider android:name="com.app.dao.MyContentProvider"
    android:authorities="com.app.test.db"
    android:exported="true" /> 

執行三次插入後的效果:

三、兩個關鍵輔助類別

UriMatcher:對傳入的 URI 進行比對,決定要操作哪一張表、要對單筆還是多筆資料動手。

ContentUris:提供便捷方法產生帶 ID 的 URI,例如 withAppendedId 與 parseId。

ContentProvider 是四大元件之一,寫的時候應該同步補上單元測試,才能確定 CRUD 行為正確。

使用單元測試的前置設定:

1)加入 instrumentation(固定寫法,也可由 ADT 精靈產生):

 <instrumentation android:name="android.test.InstrumentationTestRunner"
    android:targetPackage="com.example.android_contentprovider" >
</instrumentation> 

2)加入 uses-library(同樣是固定寫法):

 <uses-library android:name="android.test.runner" /> 

四、完整的 Provider 實作

MySQLiteOpenHelper

 package com.app.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    private static String DB_NAME = "test.db3";
    private static int VERSION = 1;

    public MySQLiteOpenHelper(Context context) {
        super(context, DB_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String create_student = "create table student("
                + "_id integer primary key autoincrement,"
                + "name varchar(10),age integer,gender varchar(10))";
        db.execSQL(create_student);
        // 千萬不要在這裡呼叫 db.close()
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    }
} 

MyContentProvider

 package com.app.contentprovider;

import com.app.db.MySQLiteOpenHelper;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class MyContentProvider extends ContentProvider {

    MySQLiteOpenHelper helper = null;

    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    private static final int student = 1;   // 單筆記錄
    private static final int students = 2;  // 多筆記錄

    static {
        matcher.addURI("com.app.wx", "student/#", student);
        matcher.addURI("com.app.wx", "student", students);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int action = matcher.match(uri);
        switch (action) {
            case student: {
                long id = ContentUris.parseId(uri);   // 取出單筆的 id
                String delete_id = "_id=" + id;
                if (selection != null) {
                    delete_id += " and " + selection;
                }
                db.delete("student", delete_id, selectionArgs);
                break;
            }
            case students:
                db.delete("student", selection, selectionArgs);
                break;
        }
        return 0;
    }

    /** 與 Intent 的 MIME 比對有關 */
    @Override
    public String getType(Uri uri) {
        int code = matcher.match(uri);
        switch (code) {
            case student:
                return "vnd.android.cursor.item/student_item";
            case students:
                return "vnd.android.cursor.dir/students";
            default:
                return null;
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int action = matcher.match(uri);
        switch (action) {
            case students: {
                long id1 = db.insert("student", "_id", values);
                Log.i("--------", ContentUris.withAppendedId(uri, id1).toString());
                return ContentUris.withAppendedId(uri, id1);
            }
        }
        return null;
    }

    @Override
    public boolean onCreate() {
        helper = new MySQLiteOpenHelper(this.getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String orderBy) {
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = null;
        int action = matcher.match(uri);
        switch (action) {
            case students:
                cursor = db.query("student", projection, selection,
                        selectionArgs, null, null, orderBy);
                break;
        }
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] arg3) {
        int count = -1;
        SQLiteDatabase db = helper.getWritableDatabase();
        int action = matcher.match(uri);
        switch (action) {
            case student: {
                long id = ContentUris.parseId(uri);
                String id_selection = "_id=" + id;
                if (selection != null && !selection.equals("")) {
                    id_selection = id_selection + " and " + selection;
                }
                count = db.update("student", values, id_selection, arg3);
                break;
            }
        }
        return count;
    }
} 

這個類別很長,但每個方法都是常見的 CRUD 樣板,真正的重點在 UriMatcher 的路徑比對與 ContentUris 的 id 解析。

五、單元測試類別

 package com.app.contentprovider;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;

public class Test extends AndroidTestCase {

    public void insert() {
        ContentResolver resolver = this.getContext().getContentResolver();
        String str = "content://com.app.wx/student";
        ContentValues values = new ContentValues();
        values.put("name", "wzq");
        values.put("age", 18);
        values.put("gender", "boy");
        resolver.insert(Uri.parse(str), values);
    }

    public void update() {
        ContentResolver resolver = this.getContext().getContentResolver();
        String str = "content://com.app.wx/student/2";
        ContentValues values = new ContentValues();
        values.put("name", "哈哈");
        resolver.update(Uri.parse(str), values, null, null);
    }

    public void query() {
        ContentResolver resolver = this.getContext().getContentResolver();
        String str = "content://com.app.wx/student";
        Uri uri = Uri.parse(str);
        Cursor cursor = resolver.query(uri,
                new String[] { "_id", "name", "age", "gender" },
                null, null, "_id desc");
        Log.d("------count", cursor.getCount() + "");
    }

    public void delete() {
        ContentResolver resolver = this.getContext().getContentResolver();
        String str = "content://com.app.wx/student/2";
        Uri uri = Uri.parse(str);
        resolver.delete(uri, null, null);
    }
} 

執行 insert(三次)之後:

執行 update 之後:

執行 query 之後:

執行 delete 之後:

幾個實務提醒

  • update 範例有個 bug 值得注意。程式碼中把 selection 與 values 字串拼接在一起當條件,這顯然是筆誤,正確應是 id_selection + " and " + selection,並把 selectionArgs 正確傳入。這也說明了為什麼 CRUD 一定要有測試覆蓋。
  • insert 應使用 ContentValues,而非寫死 SQL。第一個 demo 直接寫入固定字串只是為了簡化,正式實作要拿傳入的 values 做 insert,並回傳带 ID 的 URI,這樣呼叫方才拿得到新資料的位置。
  • exported 預設值已改變。Android 12 之後,若元件含意圖篩選條件就必須顯式宣告 android:exported;而對外開放資料時,建議搭配 android:grantUriPermissions 與 FileProvider 做最小權限的臨時授權。
  • 記得實作 getType。它回傳的 MIME 字串是跨應用互動時判斷資料型別(單筆 item / 多筆 dir)的依據,回傳 null 會讓對方無法正確處理。

以上就是 ContentProvider 從基本用法、UriMatcher 路由到單元測試的完整說明,希望對大家有所幫助。

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