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

相关推荐
Moonnnn.3 分钟前
2023年电赛C题——电感电容测量装置
笔记·学习·硬件工程
可信计算1 小时前
【xmb】】内部文档148344599
笔记
_一条咸鱼_1 小时前
Android Runtime内存管理子系统启动流程原理(13)
android·面试·android jetpack
绵绵细雨中的乡音2 小时前
Linux 学习-模拟实现【简易版bash】
linux·笔记
moxiaoran57532 小时前
uni-app学习笔记十九--pages.json全局样式globalStyle设置
笔记·学习·uni-app
航Hang*2 小时前
WEBSTORM前端 —— 第3章:移动 Web —— 第2节:空间转换、转化
前端·笔记·程序人生·edge·css3·html5·webstorm
法迪2 小时前
Android的uid~package~pid的关系
android
霸王蟹2 小时前
从前端工程化角度解析 Vite 打包策略:为何选择 Rollup 而非 esbuild。
前端·笔记·学习·react.js·vue·rollup·vite
看山还是山,看水还是。2 小时前
Linux 第三阶段课程:数据库基础与 SQL 应用
linux·运维·数据结构·数据库·数据仓库·笔记·sql
二流小码农2 小时前
鸿蒙开发:hvigorw,一个你不得不去了解的神器
android·ios·harmonyos