一、Content Provider 介绍
Content Provider 是 Android 四大组件之一,主要用于在不同应用程序之间共享数据。它提供了一种标准的机制,允许一个应用将其数据以一种安全、可控的方式暴露给其他应用。这种机制使得不同应用之间可以方便地进行数据交互,而无需直接访问彼此的内部数据存储。
例如,系统的联系人应用通过 Content Provider 共享联系人数据,其他应用(如社交应用)可以读取这些数据来帮助用户导入联系人。
二、使用 Kotlin 创建和使用 Content Provider
(一)创建 Content Provider
- 创建继承自 ContentProvider 的类
kotlin
kotlin
class MyContentProvider : ContentProvider() {
private lateinit var database: SQLiteDatabase
private val authority = "com.example.provider"
private val contentUri = Uri.parse("content://$authority/notes")
override fun onCreate(): Boolean {
val helper = DatabaseHelper(context!!)
database = helper.writableDatabase
return database!= null
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
return database.query(
"notes",
projection,
selection,
selectionArgs,
null,
null,
sortOrder
)
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
val id = database.insert("notes", null, values)
return Uri.withAppendedPath(contentUri, id.toString())
}
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<String>?
): Int {
return database.update("notes", values, selection, selectionArgs)
}
override fun delete(
uri: Uri,
selection: String?,
selectionArgs: Array<String>?
): Int {
return database.delete("notes", selection, selectionArgs)
}
override fun getType(uri: Uri): String? {
return "vnd.android.cursor.dir/vnd.example.notes"
}
}
- 定义数据库帮助类
kotlin
kotlin
class DatabaseHelper(context: Context) : SQLiteOpenHelper(
context,
"notes.db",
null,
1
) {
override fun onCreate(db: SQLiteDatabase) {
val createTable = "CREATE TABLE notes (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"content TEXT)"
db.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS notes")
onCreate(db)
}
}
- 在 AndroidManifest.xml 中注册 Content Provider
xml
ini
<provider
android:name=".MyContentProvider"
android:authorities="com.example.provider"
android:exported="true" />
(二)使用 Content Provider
-
获取 ContentResolver
在需要访问 Content Provider 的组件(如 Activity)中获取
ContentResolver
。
kotlin
ini
val resolver = contentResolver
-
执行操作
- 查询数据
kotlin
kotlin
val uri = Uri.parse("content://com.example.provider/notes")
val projection = arrayOf("_id", "title", "content")
val cursor = resolver.query(uri, projection, null, null, null)
cursor?.use {
while (it.moveToNext()) {
val id = it.getLong(it.getColumnIndex("_id"))
val title = it.getString(it.getColumnIndex("title"))
val content = it.getString(it.getColumnIndex("content"))
Log.d("ContentProvider", "ID: $id, Title: $title, Content: $content")
}
}
- 插入数据
kotlin
kotlin
val uri = Uri.parse("content://com.example.provider/notes")
val values = ContentValues().apply {
put("title", "New Note")
put("content", "This is a new note.")
}
val insertedUri = resolver.insert(uri, values)
insertedUri?.let {
Log.d("ContentProvider", "Inserted note at: $it")
}
- 更新数据
kotlin
ini
val uri = Uri.parse("content://com.example.provider/notes")
val values = ContentValues().apply {
put("content", "Updated content")
}
val selection = "_id =?"
val selectionArgs = arrayOf("1")
val count = resolver.update(uri, values, selection, selectionArgs)
Log.d("ContentProvider", "Updated $count rows.")
- 删除数据
kotlin
ini
val uri = Uri.parse("content://com.example.provider/notes")
val selection = "_id =?"
val selectionArgs = arrayOf("1")
val count = resolver.delete(uri, selection, selectionArgs)
Log.d("ContentProvider", "Deleted $count rows.")
通过以上步骤,就可以使用 Kotlin 实现一个简单的 Content Provider,并在应用中对其进行数据的增删改查操作。在实际应用中,还需要根据具体需求进行更复杂的权限管理和数据处理。