android ContentProvider 跨进程通信

205 阅读1分钟

1 定义Provider

class DataProvider : ContentProvider() {}

2 xml中声明

       <provider
            android:authorities="com.gy.commonviewdemo.provider"
            android:name=".db.DataProvider"
            android:exported="true"/>

3 业务app中调用

                    val uri = Uri.parse("content://com.gy.commonviewdemo.provider/")
                    val contentValues = ContentValues()
                    contentValues.put("name", "gy")
                    contentValues.put("value", "123456")
                    val resultUri = contentResolver.insert(uri, contentValues)
                    val code = resultUri?.getQueryParameter("value") //code 为code_132

4 在ContentProvider中接收数据并处理

    override fun insert(uri: Uri, values: ContentValues?): Uri {
        if (values == null) {
            return uri
        }
        val name = values.getAsString("name")
        val password = values.getAsString("password")
        return  Uri.parse("content://${context?.packageName}?value=code_132")
    }

5 权限

  <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>