Android四大组件之ContentProvider

2023-02-01  本文已影响0人  文泰ChrisTwain

1.简介

They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications.

三剑客:

2.使用

(1)URI简介

统一资源标志符(Uniform Resource Identifier,缩写:URI)
一种统一约定的格式化字符串


ContentProvider通过URI区分不同的数据,部分解析方法如下
Uri uri = Uri.parse("content://sms/inbox"); // URI对应的封装类
List<String> pathSegments = uri.getPathSegments(); // 获取URI的Segment列表
String dtbName = pathSegments.get(0); // 按序读取Segment值,此处返回值为inbox,一般authority字段之后跟着具体的表名,可解析读取后进行自身逻辑处理
Android中内置了许多常用URI,比如

管理联系人的Uri:
ContactsContract.Contacts.CONTENT_URI 
管理联系人的电话的Uri:
ContactsContract.CommonDataKinds.Phone.CONTENT_URI 
管理联系人的Email的Uri:
ContactsContract.CommonDataKinds.Email.CONTENT_URI 
发送箱中的短信URI:
Content://sms/outbox
收信箱中的短信URI:
Content://sms/sent
草稿中的短信URI:
Content://sms/draft
(2)举例1:读取电话簿
try (Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null, null, null, null)) {
    while (cursor.moveToNext()) {
        // 姓名
        String displayName = cursor.getString(
                cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        // 手机号
        String number = cursor.getString(
                cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.d(TAG, "readContacts: displayName = " + displayName + " --- number = " + number);
    }
} catch (Exception e) {
    e.printStackTrace();
}
(3)举例2:监听设置变化

设置APP中的开关会将设置值写入xml文件,可通过ContentResolver进行监听
两大方法:
context.getContentResolver().notifyChange(uri, null) // 通知所有uri数据变更
context.getContentResolver().registerContentObserver(uri, boolean notifyForDescendants, contentObserver) // 监听消息
registerContentObserver()方法第二个参数官方注释如下:由于URI有多段,用于确认匹配URI的精度
When false, the observer will be notified whenever a change occurs to the exact URI specified by uri or to one of the URI's ancestors in the path hierarchy.
当传false 时,只要uri指定的确切 URI 或路径层次结构中 URI 的祖先之一发生更改,就会通知观察者。
When true, the observer will also be notified whenever a change occurs to the URI's descendants in the path hierarchy.
传true时,只要路径层次结构中 URI 的后代发生更改,观察者也会收到通知

假设我们当前需要观察的Uri为content://com.me.test/student,如果发生数据变化的Uri为
content://com.me.test/student/schoolchild,当notifyForDescendents为false,那么该ContentObserver会监听不到
但是当notifyForDescendents为ture,能捕捉该Uri的数据变化。

具体读取逻辑 Android系统属性和设置项读取 可参考第二节

(4)举例3:实现ContentProvider

AndroidManifest配置组件信息

<provider
    android:name="com.me.test.server.storagemanager.MyContentProvider"
    android:readPermission="com.me.test.permission.READ_PROVIDER"
    android:writePermission="com.me.test.permission.WRITE_PROVIDER"
    android:authorities="com.me.test.provider"
    android:enabled="true"
    android:exported="true" />

可借助UriMatcher匹配对应的入参URI,也可以将传入的URI toString后自行处理URI字符串

public class MyContentProvider extends ContentProvider {
    private static UriMatcher uriMatcher;

    @Nullable
    @Override
    public Bundle call(@NonNull String method, @Nullable String arg, @Nullable Bundle extras) {
        switch (method) {
            case "xxx":
            default:
        }
        return null;
    }

    @Override
    public boolean onCreate() {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI("com.me.test.provider", "table1", 1);
        return true;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return uri;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        switch (uriMatcher.match(uri)) {
            case TABLE1_DIR:
                //查询 table1 表中的所有数据
                break;
        }
        Cursor cursor = null;
        // 实现数据操作逻辑...
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        return 0;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

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

外部应用操作数据

ContentResolver cr = context.getContentResolver();
cr.query();
cr.insert();  // 单条插入
cr.bulkInsert();  // 批量插入
cr.update();
cr.delete();
cr.call();  // 可调用call方法来调用ContentProvider的自定义方法,call有一个字符串用来标识方法名,入参出参通过Bundle传递
cr.getType();  // 根据传入的内容URI返回相应的数据,可用于获取某些给外部应用预知的数据,

3.原理

通过IBinder实现通信过程
getContentResolver获得到的是ApplicationContentResolver(在ContextImpt中实现)
Client端ApplicationContentResolver使用ContentProviderProxy作为IBinder的Proxy(ContentProviderNative中实现)
Provider端通过Transport作为IBinder的实现端(ContentProvider中实现)
getContentResolve->ApplicationContentResolver->ContentProviderProxy<===IBidner====>Transport->NameProvider

注意ContentProvider onCreate()执行在Application onCreate()之前,避免ContentProvider创建时对其它还未初始化对象有依赖,否则可能导致crash

MyApplication: Application attachBaseContext()
MyApplication: MyContentProvider onCreate()
MyApplication: MyContentProvider attachInfo()
MyApplication: Application onCreate()

部分Android库如Picasso、LeakCanary将自身初始化操作放到ContentProvider onCreate()中自动初始化

参考

Android探索之ContentProvider熟悉而又陌生的组件
对ContentProvider中getType方法的一点理解
LeakCanary源码分析以及ContentProvider的优化方案

上一篇 下一篇

猜你喜欢

热点阅读