android
的四大组件,已经介绍了两个,这一节介绍ContentProvider
。前面的广播可以进行 app内的通讯,如果需要进行app之间的通讯,在android
中使用的是ContentProvider
。ContentProvider
也分为三种,一,作为数据的存储和查询,也就是别人来调用你ContentProvider
。二,调用者ContentResolver
,用来调用插入和查询数据。三,观察者ContentObserver
,比如监控短信的变化。
ContentProvider
提供者
ContentProvider
提供者作为一个母体,用来通过数据的查询和插入,这样做的好处是,让每个服务都相互独立,而且有可以像外部提供相应的接口。比如通讯录,短信息等。他们作为一种服务,根据用户的权限来提供特有的服务。
这里我们也建立一个ContentProvider
,用户可以来调用,提供查询和插入的功能。我们用sqlite
对数据进行存储和查询。
inner class DBHelper(context:Context,name:String,
factory:SQLiteDatabase.CursorFactory?,version:Int):SQLiteOpenHelper(context,name,factory, version){
override fun onCreate(_db: SQLiteDatabase?) {
var sql:String = "CREATE TABLE " + DATUM_TABLE_NAME +
" (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
Constants.TEXT+
" VARCHAR(20)" + ")"
_db?.execSQL(sql)
}
override fun onUpgrade(_db: SQLiteDatabase?, p1: Int, p2: Int) {
var sql:String = "DROP TABLE IF EXISTS " + DATUM_TABLE_NAME
_db?.execSQL(sql)
onCreate(_db)
}
}
创建 ContentProvider
class DataProvider : ContentProvider()
实现两个接口 query
,insert
。
override fun query(
uri: Uri,
p: Array<out String>?,
s: String?,
args: Array<out String>?,
sort: String?
): Cursor? {
val qb = SQLiteQueryBuilder()
qb.tables = DATUM_TABLE_NAME
qb.projectionMap = projMap
var s1 = s
if (sUriMatcher.match(uri) != DATUM) {
if (sUriMatcher.match(uri) == DATUM_ID)
s1 = s + "_id = " + uri?.lastPathSegment
else
throw IllegalArgumentException("Unknown URI " + uri)
}
val db = dbHelper?.readableDatabase
val c = qb.query(db, p, s1, args, null, null, sort)
c.setNotificationUri(context?.contentResolver ?: null, uri)
return c
}
insert
接口
override fun insert(uri: Uri, cv: ContentValues?): Uri? {
var m:Int = sUriMatcher.match(uri).toInt()
m = 1
if (m != 1){
throw IllegalArgumentException("Unknown URI " + uri)
}
val v: ContentValues
if (cv != null)
v = ContentValues(cv)
else
v = ContentValues()
val db = dbHelper?.writableDatabase
val rId = db?.insert(DATUM_TABLE_NAME, Constants.TEXT, v)
if (rId != null) {
if (rId > 0) {
val uri = ContentUris.withAppendedId(Constants.URL, rId)
context?.contentResolver?.notifyChange(uri, null)
return uri
}
} else {
throw SQLException("Failed to insert row into " + uri)
}
return null
}
如何调用呢?
var textView = findViewById<TextView>(R.id.textView)
var btn = findViewById<Button>(R.id.btn)
// Inserting data into content provider
val tuple = ContentValues()
tuple.put(Constants.TEXT, Constants.TEXT_DATA)
contentResolver.insert(Constants.URL, tuple)
// Reading from content provider
val cols = arrayOf(Constants.ID, Constants.TEXT)
val u = Constants.URL
val c = contentResolver.query(u, cols, null, null, null)
if (c!!.moveToLast())
textView.text = "Data read from content provider: " +
c!!.getString(c.getColumnIndex(Constants.TEXT))
else
textView.text = "Access denied"
在AndroidManifest.xml
上 添加:
<provider
android:name="com.kotlin.kotlin_start_ch16.DataProvider"
android:authorities="com.kotlin.kotlin_start_ch16.provider"
android:exported="true"
android:multiprocess="true"/>
模拟插入数据后,对数据进行查询,并显示在textview
上。
contentResolver 获取短信数据
app
获取短信需要相应的权限,首先要确认和申请权限。在AndroidManifest.xml
上添加,
<uses-permission android:name="android.permission.READ_SMS" />
这样还不够,需要进行权限的用户授权。
fun checkPermission():Boolean{
var result = ContextCompat.checkSelfPermission(applicationContext,Manifest.permission.READ_SMS)
return result==PackageManager.PERMISSION_GRANTED
}
fun requestPermission(i:Int){
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_SMS),i)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
当用户确认以后,才可以进行短信的获取。
if (!checkPermission()){
requestPermission(123)
}
btn.setOnClickListener {
val cols = arrayOf("_id","address","date","type","body")
var c = contentResolver.query(Uri.parse("content://sms/"),cols,null,null, null)
while (c!!.moveToNext()){
var body=c.getString(4)
textView.text = body
var s = SmsInfo(c.getInt(0),c.getString(1),c.getLong(2),c.getString(4))
sms.add(s)
}
var text:String = ""
sms.forEach{
text = text + it.address + "\n"
text = text + it.info + "\n"
}
textView.text = text
}
ContentObserver
监控短信的到来
ContentObserver
监控短信同样的需要相应的权限,可以看看上节的代码,要监控短信需要新建一个类继承ContentObserver
,并进行注册:
smsContentObserver = SmsContentObserver(this, Handler(Looper.getMainLooper()), conversationsHandler)
//smsContentObserver = SmsContentObserver(this, Handler(Looper.getMainLooper()))
smsContentObserver?.let {
//it.start()
contentResolver.registerContentObserver(Telephony.Sms.CONTENT_URI, true, it)
contentResolver.registerContentObserver(Telephony.Mms.CONTENT_URI, true, it)
contentResolver.registerContentObserver(Telephony.MmsSms.CONTENT_URI, true, it)
}
收到短信后,对短信进行处理:
private fun newSms() {
val newSms: Map<Int, SmsObject> = smsDeleteDetector.newSms()
newSms.forEach {
if ((it.value._type).toInt() == Telephony.Sms.Inbox.MESSAGE_TYPE_INBOX) {
logToastHelper.showLogMsg(
context,
"$tag Inbox ID:${it.value._id} ThreadId:${it.value._threadId} ",
"SMS From ${it.value._address} : ${it.value._body}"
)
} else if (((it.value._type).toInt()) == Telephony.Sms.Inbox.MESSAGE_TYPE_SENT) {
logToastHelper.showLogMsg(
context,
"$tag Outbox ID:${it.value._id} ThreadId:${it.value._threadId}",
"SMS Sent To ${it.value._address} : ${it.value._body}"
)
}
}
}
小结
如果一步一步的进行安卓基础知识的学习,会觉得android的设计还是很有层次的,每一组组件都设计的比较完善,编程者用起来其实都会觉得比较简单的。