安卓Content Provider介绍及使用

一、Content Provider 介绍

Content Provider 是 Android 四大组件之一,主要用于在不同应用程序之间共享数据。它提供了一种标准的机制,允许一个应用将其数据以一种安全、可控的方式暴露给其他应用。这种机制使得不同应用之间可以方便地进行数据交互,而无需直接访问彼此的内部数据存储。

例如,系统的联系人应用通过 Content Provider 共享联系人数据,其他应用(如社交应用)可以读取这些数据来帮助用户导入联系人。

二、使用 Kotlin 创建和使用 Content Provider

(一)创建 Content Provider

  1. 创建继承自 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"
    }
}
  1. 定义数据库帮助类

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)
    }
}
  1. 在 AndroidManifest.xml 中注册 Content Provider

xml

ini 复制代码
<provider
    android:name=".MyContentProvider"
    android:authorities="com.example.provider"
    android:exported="true" />

(二)使用 Content Provider

  1. 获取 ContentResolver

    在需要访问 Content Provider 的组件(如 Activity)中获取 ContentResolver

kotlin

ini 复制代码
val resolver = contentResolver
  1. 执行操作

    • 查询数据

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,并在应用中对其进行数据的增删改查操作。在实际应用中,还需要根据具体需求进行更复杂的权限管理和数据处理。

相关推荐
William Dawson5 小时前
2026软考中级系统集成项目管理工程师备考笔记
笔记·系统集成项目管理工程师
liang_jy7 小时前
Android SparseArray
android·源码
liang_jy7 小时前
Activity 启动流程扩展篇(一)—— startActivityInner 任务决策全解析
android·源码
love530love8 小时前
精简版|Claude-HUD 插件介绍 + 一键安装教程
人工智能·windows·笔记
想成为优秀工程师的爸爸8 小时前
第三十篇技术笔记:郭大侠学UDS - 人有生老三千疾,望闻问切良方医
网络·笔记·网络协议·tcp/ip·信息与通信
NPE~8 小时前
[App逆向]脱壳实战
android·教程·逆向·android逆向·逆向分析
木易 士心9 小时前
别再只会用 drawCircle 了!一文搞懂 Android Canvas 底层机制
android
tq108610 小时前
数学:约束表征空间的最小闭包
笔记
AtOR CUES10 小时前
MySQL——表操作及查询
android·mysql·adb
freexyn11 小时前
Matlab自学笔记七十六:表达式的展开、因式分解、化简、合并同类项
笔记·算法·matlab