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

相关推荐
RLG_星辰1 小时前
第六章-哥斯拉4.0流量分析与CVE-2017-12615的复现
笔记·安全·网络安全·tomcat·应急响应·玄机
敦普水性工业漆6 小时前
汽车紧固件防腐3.0时代:敦普水性漆用无铬锌铝涂层定义「零氢脆」标准
笔记·汽车
JhonKI6 小时前
【MySQL】存储引擎 - CSV详解
android·数据库·mysql
开开心心_Every6 小时前
手机隐私数据彻底删除工具:回收或弃用手机前防数据恢复
android·windows·python·搜索引擎·智能手机·pdf·音视频
大G哥7 小时前
Kotlin Lambda语法错误修复
android·java·开发语言·kotlin
TUTO_TUTO8 小时前
【AWS+Wordpress】将本地 WordPress 网站部署到AWS
笔记·学习·云计算·aws
大溪地C9 小时前
CSS详细学习笔记
css·笔记·学习
chennalC#c.h.JA Ptho10 小时前
Centos系统详解架构详解
linux·经验分享·笔记·系统架构·系统安全
饕餮争锋10 小时前
Spring普通配置类 vs 自动配置类-笔记
java·笔记·spring
Aimyon_3610 小时前
Java复习笔记-基础
java·开发语言·笔记