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

相关推荐
江太翁13 分钟前
mediapipe流水线分析 三
android·mediapipe
kikikidult41 分钟前
(2025.07)解决——ubuntu20.04系统开机黑屏,左上角光标闪烁
笔记·ubuntu
与火星的孩子对话42 分钟前
Unity进阶课程【六】Android、ios、Pad 终端设备打包局域网IP调试、USB调试、性能检测、控制台打印日志等、C#
android·unity·ios·c#·ip
近津薪荼1 小时前
初学者关于数据在内存中的储存的笔记
笔记
tmacfrank2 小时前
Android 网络全栈攻略(四)—— TCPIP 协议族与 HTTPS 协议
android·网络·https
fundroid3 小时前
Kotlin 协程:Channel 与 Flow 深度对比及 Channel 使用指南
android·kotlin·协程
碎叶城李白3 小时前
若依学习笔记1-validated
java·笔记·学习·validated
草字3 小时前
cocos 打包安卓
android
DeBuggggggg4 小时前
centos 7.6安装mysql8
android
HuashuiMu花水木5 小时前
PyTorch笔记1----------Tensor(张量):基本概念、创建、属性、算数运算
人工智能·pytorch·笔记