ContentProvider內(nèi)容提供者,主要用于再不同的應(yīng)用程序之前實(shí)現(xiàn)數(shù)據(jù)共享的功能,它提供了一套完整的機(jī)制,允許一個(gè)程序訪問(wèn)另外一個(gè)程序的數(shù)據(jù),同時(shí)還能保證數(shù)據(jù)的安全性。通訊錄的聯(lián)系人信息,短信信息,媒體庫(kù)信息等都通過(guò)這個(gè)方式把數(shù)據(jù)共享出來(lái),第三方可以獲取到進(jìn)行二次開(kāi)發(fā)。
1.ContentProvider訪問(wèn)程序的數(shù)據(jù)
contentProvider的用法有兩種
- 使用現(xiàn)用的ContentProvider訪問(wèn)相應(yīng)程序的數(shù)據(jù)。
- 創(chuàng)建自己的contentProvider給程序的數(shù)據(jù)提供外部訪問(wèn)接口。
如果向訪問(wèn)共享的數(shù)據(jù)需要借助ContentResolver,這個(gè)類(lèi)提供了一系列的方法對(duì)數(shù)據(jù)進(jìn)行增刪查改操作:insert、update、delete、query
ContentResolver通過(guò)URI來(lái)訪問(wèn)數(shù)據(jù),URI字符串的格式 content://程序包名.provider/表名
2.ContentResolver 使用
- 查詢數(shù)據(jù)
public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri,
@Nullable String[] projection, @Nullable String selection,
@Nullable String[] selectionArgs, @Nullable String sortOrder) {
return query(uri, projection, selection, selectionArgs, sortOrder, null);
}
Uri:確定了訪問(wèn)數(shù)據(jù)的唯一標(biāo)識(shí),指定查詢某個(gè)應(yīng)用程序下的某一張表
projection:指定查詢的列名字,是一個(gè)字符串,可以同時(shí)指定多個(gè)列名字。
selection:指定where的約束條件。
selectionArgs:為where中的占位符提供具體的值。
sortOrder:指定結(jié)果的排序方式。
這個(gè)方法返回一個(gè)Cursor對(duì)象,使用Cursor遍歷得到的數(shù)據(jù)
while (cursor?.moveToNext()!!){
val column1 = cursor.getString(cursor.getColumnIndex("column1"))
val column2 = cursor.getString(cursor.getColumnIndex("column2"))
}
cursor.close()
- 插入數(shù)據(jù)
val values= contentValuesOf("columu1" to "content","column2" to 1)
contentResolver.insert(Uri.parse(uri),values)
- 更新數(shù)據(jù)
val valuesUpdate= contentValuesOf("column1" to "")
contentResolver.update(Uri.parse(uri),values,"column1 = ? and column2 = ?", arrayOf("text","1"))
使用selection selectionArgs 參數(shù)對(duì)想要更新的數(shù)據(jù)進(jìn)行約束,防止所有的數(shù)據(jù)都會(huì)收到影響
- 刪除數(shù)據(jù)
contentResolver.delete(Uri.parse(uri),"column2 = ?", arrayOf("1"))
3.使用ContentProvider讀取聯(lián)系人的數(shù)據(jù)
if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS),1)
}else{
readContacts()
}
讀取系統(tǒng)聯(lián)系人需要?jiǎng)討B(tài)申請(qǐng)權(quán)限,先確認(rèn)程序是否具備READ_CONTACTS權(quán)限,如果存在權(quán)限,讀取聯(lián)系人數(shù)據(jù),不存在就申請(qǐng)權(quán)限。
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when(requestCode){
1->{
if (grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
readContacts()
}else{
showToast("you denied the permission")
}
}
}
}
請(qǐng)求權(quán)限之后,不管用戶是否給權(quán)限都會(huì)回調(diào)onRequestPermissionsResult方法,如果用戶點(diǎn)擊允許執(zhí)行讀取聯(lián)系人的邏輯,否則給Toast提示
private fun readContacts() {
mDatas.clear()
contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
null,null,null)?.apply {
while (moveToNext()){
val displayName=getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
val number=getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
val contacts=Contacts(name = displayName,number =number )
mDatas.add(contacts)
}
}
contactAdapter.setData(mDatas)
}
讀取聯(lián)系人信息,并遍歷cursor數(shù)據(jù),獲取到名字和手機(jī)號(hào)碼
ContactsContract.CommonDataKinds.Phone.CONTENT_URI:這個(gè)是數(shù)據(jù)庫(kù)Uri
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME:這個(gè)是指名稱(chēng)的列名字
ContactsContract.CommonDataKinds.Phone.NUMBER:這個(gè)是手機(jī)號(hào)的列名字
4.通過(guò)ContentProvider暴露自己程序的數(shù)據(jù)接口
class DatabaseProvider : ContentProvider() {
private val bookDir = 0
private val bookItem = 1
private val authority = "com.test.kotlin_test.provider"
private var dbHelper : MySqliteDataHelper ?= null
private val uriMatcher by lazy {
val mathcher=UriMatcher(UriMatcher.NO_MATCH)
mathcher.addURI(authority,"book",bookDir)
mathcher.addURI(authority,"book/#",bookItem)
mathcher
}
override fun insert(uri: Uri, values: ContentValues?)=dbHelper?.let {
val db =it.writableDatabase
val uriReturn=when(uriMatcher.match(uri)){
bookDir ->{
val newBookId=db.insert("Book",null,values)
Uri.parse("content://$authority/book/$newBookId")
}
else ->null
}
uriReturn
}
override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?
) = dbHelper?.let {
val db=it.readableDatabase
val cursor = when(uriMatcher.match(uri)){
bookDir ->db.query("Book",projection,selection,selectionArgs,null,null,sortOrder)
bookItem -> {
val bookId=uri.pathSegments[1]
db.query("Book",projection,"id=?", arrayOf(bookId),null,null,sortOrder)
}
else->null
}
cursor
}
override fun onCreate() = context?.let {
dbHelper=MySqliteDataHelper(it,"BookStore.db",2)
true
} ?:false
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?)= dbHelper?.let {
val db=it.writableDatabase
val updateRows=when(uriMatcher.match(uri)){
bookDir -> db.update("Book",values,selection,selectionArgs)
bookItem ->{
val bookId=uri.pathSegments[1]
db.update("Book",values,"id=?", arrayOf(bookId))
}
else -> 0
}
updateRows
} ?: 0
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?)=dbHelper?.let {
val db=it.writableDatabase
val deleteRows=when(uriMatcher.match(uri)){
bookDir -> db.delete("Book",selection,selectionArgs)
bookItem -> {
val bookId=uri.pathSegments[1]
db.delete("Book","id=?", arrayOf(bookId))
}
else->0
}
deleteRows
}?: 0
override fun getType(uri: Uri)=when(uriMatcher.match(uri)){
bookDir -> "vnd.android.cursor.dir/vnd.com.test.kotlin_test.provider.book"
bookItem -> "vnd.android.cursor.item/vnd.com.test.kotlin_test.provider.book"
else -> null
}
}
- 在by lazy 塊里邊對(duì)uriMatcher進(jìn)行初始化,開(kāi)始的時(shí)候并不會(huì)進(jìn)行加載,只有當(dāng)uriMatcher首次進(jìn)行調(diào)用的時(shí)候才會(huì)執(zhí)行
<provider android:authorities="com.test.kotlin_test.provider"
android:enabled="true"
android:exported="true"
android:name=".content_provider.DatabaseProvider"/>
在清單文件進(jìn)行注冊(cè),exported是否允許外部程序訪問(wèn),enabled是否啟動(dòng)這個(gè)提供者
val uri=Uri.parse("content://com.test.kotlin_test.provider/book")
contentResolver.query(uri,null,null,null,null)?.apply {
while (moveToNext()){
val name=getString(getColumnIndex("name"))
val author=getString(getColumnIndex("author"))
val pages=getInt(getColumnIndex("pages"))
val price=getDouble(getColumnIndex("price"))
Log.d(TAG,"anme=$name,author=$author,price=$price,pages=$pages")
}
}
通過(guò)我們自己的提供者進(jìn)行數(shù)據(jù)查詢,并將結(jié)果打印出來(lái)
val uri=Uri.parse("content://com.test.kotlin_test.provider/book")
val contentValuesOf =
contentValuesOf("name" to "Kings of the world", "author" to "kings", "pages" to 1001, "price" to 22.68)
val newUri = contentResolver.insert(uri, contentValuesOf)
bookId = newUri?.pathSegments?.get(1)
通過(guò)我們自己的內(nèi)容提供者插入一條數(shù)據(jù)
val uri=Uri.parse("content://com.test.kotlin_test.provider/book")
val contentValue=contentValuesOf("price" to 14)
contentResolver.update(uri,contentValue,"name=?", arrayOf("Kings of the world"))
通過(guò)我們自己的內(nèi)容提供者插入更新一條數(shù)據(jù)
val uri=Uri.parse("content://com.test.kotlin_test.provider/book")
contentResolver.delete(uri,"name=?", arrayOf("Kings of the world"))
通過(guò)我們自己的內(nèi)容提供者刪除一條數(shù)據(jù)
上面的幾個(gè)部分可以已經(jīng)測(cè)試均正確沒(méi)有錯(cuò)位。