目錄
- 寫在前面的話
- 一、內容提供者
- (一)概述
- (二)測驗
- 二、內容觀察者
- (一)概述
- (二)測驗
- 三、補充
寫在前面的話
1、參考自:https://b23.tv/0VmCjN
2、內容如有不對的,希望可以指出或補充,
3、新知識,
一、內容提供者
(一)概述
內容提供者(ContentProvider):是Android系統四大組件之一,它是不同應用程式之間進行資料共享的標準API,通過內容決議者(ContentResolver)類可以訪問內容提供者中共享的資料,
內容決議者(ContentResolver):提供一系列增刪改查的方法對資料進行操作,并且這些方法以Uri的形式對外提供資料,
統一資源標志符(Uniform Resource Identifier,URI)):為內容提供者中的資料建立了唯一識別符號,主要由:scheme(命名機制;這部分(內容提供者)固定為content://)、authorities(存資源的主機名;通常采取程式包名的方式來命令)和path(資源名稱;代表資源或資料,可以動態改變)三部分組成,如:content://cn.luck.mycontentprovider/test
(二)測驗
大概步驟(通過內容決議者訪問內容提供者):獲取相應操作的Uri→獲取ContentResolver物件→通過ContentResolver物件查詢資料
內容提供者的創建:同廣播與服務的創建類似(在程式包名上右擊選擇【New】→【Other】→【Content Provider】→在彈出的視窗中輸入類名稱或默認,再填寫好URI Authorities即可);若采用自行創建Java類繼承ContentProvider類的方式創建服務,則需要手動在【專案清單檔案】中進行注冊,
例子(通過內容決議者訪問內容提供者)-查看手機上的短信,
存短信資料的資料庫:
找到如下位置的(Android Studio界面右下角)點擊打開,在當前正在運行的設備資訊中,找到 data→data→ com.android.providers.telephony 包→databases→mmssms.db檔案 就是當前設備系統存短信資料的資料庫檔案,

右擊mmssms.db選擇Save As…進行保存,通過navicat打開,檔案內容如下,
1、布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@mipmap/bg">
<!--按鈕-->
<ImageButton
android:id="@+id/btn"
android:onClick="readSMS"
tools:ignore="OnClick"
android:layout_width="80dp"
android:layout_height="50dp"
android:background="@mipmap/btn_bg"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:layout_marginTop="100dp" />
<!--android:visibility="invisible"設定內容為不可見-->
<TextView
android:id="@+id/tv_title"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/btn"
android:layout_marginTop="30dp"
android:paddingLeft="60dp"
android:textSize="15sp"
android:text="讀取到的短信內容:"
android:visibility="invisible"
android:textColor="@color/black"/>
<TextView
android:id="@+id/tv_text"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/tv_title"
android:paddingLeft="60dp"
android:textSize="15sp"/>
</RelativeLayout>
2、代碼
MainActivity.java
package com.example.testcontentprovider;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView tvTitle, tvText;
private String content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取控制元件
tvTitle = findViewById(R.id.tv_title);
tvText = findViewById(R.id.tv_text);
}
//按鈕事件
public void readSMS(View view){
//查詢系統資訊的uri
// Uri.parse()方法是將字串轉換成Uri物件
//sms為系統短信的uri中的authorities地址
Uri uri = Uri.parse("content://sms/");
//獲取到內容決議者物件
ContentResolver resolver = getContentResolver();
//查詢資料
Cursor cursor = resolver.query(uri, new String[]{"_id","address","type","body","date"},
null,null,null);
//創建一個集合遍歷cursor(游標
List<SmsInfo> smsInfos = new ArrayList<>();
//判斷cursor不為空且查出的內容大于0條資料
if(cursor !=null && cursor.getCount()>0) {
tvTitle.setVisibility(View.VISIBLE);//顯示為可見
//從cursor獲取到相應內容
while (cursor.moveToNext()){
int _id = cursor.getInt(0);
String address = cursor.getString(1);
int type = cursor.getInt(2);
String body = cursor.getString(3);
long date = cursor.getLong(4);
//創建SmsInfo物件
SmsInfo smsInfo = new SmsInfo(_id,address,type,body,date);
smsInfos.add(smsInfo);//添加到集合中
}
cursor.close();
}
//將查詢到的內容顯示到界面上
for(int i = 0; i < smsInfos.size(); i++){
content = "手機號碼:"+smsInfos.get(i).getAddress()+"\n";
content += "短信內容:"+smsInfos.get(i).getBody()+"\n";
tvText.setText(content);
}
}
}
SmsInfo.java
package com.example.testcontentprovider;
//相當于短信資訊的介面
public class SmsInfo {
private int _id;//短信主鍵
private String address;//發送地址
private int type;//型別
private String body;//短信內容
private long date;//時間
public SmsInfo(int _id, String address, int type, String body, long date) {
this._id = _id;
this.address = address;
this.type = type;
this.body = body;
this.date = date;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
}
3、效果
設定權限宣告:

運行效果如下:

二、內容觀察者
Day16內容,
新知識,
(一)概述
內容觀察者(ContentObserver):用來觀察指定Uri所代表的資料的,當內容觀察者觀察到指定Uri代表的資料發生變化時,就會觸發onChange()方法,在該方法中使用內容觀察者可以查詢到變化的資料,
使用內容觀察者(觀察資料變化)的前提:必須在內容提供者(ContentProvider)的delete()、insert()、update()方法中呼叫內容決議者(ContentResolver)的notifyChange()方法,
(二)測驗
ContentObserver的兩個常用方法:
① public ContentObserver(Handler handler)
ContentObserver的派生類(子類)都需要呼叫這個構造方法,引數可以為執行緒(Handler),也可以為任何Handler(Android系統中執行緒間傳遞訊息的一種機制)物件,
② public void onChange(boolean selfChange)
當觀察的Uri代表的資料發生改變時,會觸發這個方法,在這個方法中使用ContentResolver可以查詢到變化的資料,
使用內容觀察者來觀察資料的大致步驟:
創建一個內容決議者→通過內容決議者呼叫registerContentObserver()這個方法,把某一個內容觀察者注冊到一個uri上
例子-檢測資料庫的變化
1、布局

2、代碼
SQLiteOpenHelper

PersonProvider.java
-內容提供者
package com.example.testcontentobserver;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class PersonProvider extends ContentProvider {
public PersonProvider() {
}
private PersonDBOpenHelper helper;//成員變數
//定義uri路徑匹配器
//路徑匹配不成功回傳-1
private static UriMatcher uriMatcher = new UriMatcher(-1);
//匹配成功回傳1
private static final int SUCCESS = 1;
//靜態代碼塊
//添加具體的路徑匹配規則
static {
uriMatcher.addURI("cn.luck.contentobserverdb","info",SUCCESS);
}
@Override
//洗掉資料的操作
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
int code = uriMatcher.match(uri);//匹配查詢的uri路徑
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();//拿到資料庫
int count = db.delete("info",selection,selectionArgs);//洗掉了幾行
if(count > 0){//洗掉成功,資料發生改變
//提示資料庫資料發生改變了
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else{
//拋出非法引數不正常例外
throw new IllegalArgumentException("路徑錯誤,不洗掉資料");
}
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
//添加資料的操作
public Uri insert(Uri uri, ContentValues values) {
// TODO: Implement this to handle requests to insert a new row.
int code = uriMatcher.match(uri);//匹配查詢的uri路徑
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();//拿到資料庫
long rowId = db.insert("info",null,values);//插入到哪一行
if(rowId > 0){//插入成功
//獲取到插入到對應行的Uri
Uri insertedUri = ContentUris.withAppendedId(uri,rowId);
//提示資料庫資料發生改變了
getContext().getContentResolver().notifyChange(insertedUri,null);
return insertedUri;
}
db.close();
return null;//插入失敗
}else{
//拋出非法引數不正常例外
throw new IllegalArgumentException("路徑錯誤,不添加資料");
}
}
@Override
public boolean onCreate() {
// TODO: Implement this to initialize your content provider on startup.
helper = new PersonDBOpenHelper(getContext());
return false;
}
@Override
//查詢資料的操作
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO: Implement this to handle query requests from clients.
int code = uriMatcher.match(uri);//匹配查詢的uri路徑
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();//拿到資料庫
//查詢info表
return db.query("info",projection,selection,selectionArgs,
null,null,sortOrder);
}else{
//拋出非法引數不正常例外
throw new IllegalArgumentException("路徑錯誤,不提供資料");
}
}
@Override
//更新資料的操作
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
int code = uriMatcher.match(uri);//匹配查詢的uri路徑
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();//拿到資料庫
int count = db.update("info",values,selection,selectionArgs);//影響了幾行
if(count > 0){
//提示資料庫資料發生改變了
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else{
//拋出非法引數不正常例外
throw new IllegalArgumentException("路徑錯誤,不更新資料");
}
}
}
MainActivity.java
package com.example.testcontentobserver;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button addBtn,updateBtn,deleteBtn,selectBtn;
private ContentResolver contentResolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();//初始化界面
createDB();//創建資料庫
}
private void initView() {
//獲取到界面控制元件
addBtn = findViewById(R.id.add_btn);
updateBtn = findViewById(R.id.update_btn);
deleteBtn = findViewById(R.id.delete_btn);
selectBtn = findViewById(R.id.select_btn);
//系結監聽器
addBtn.setOnClickListener(this);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
selectBtn.setOnClickListener(this);
}
private void createDB() {
PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
for (int i = 0; i < 4; i++) {
ContentValues values = new ContentValues();
values.put("name","test"+i);//這樣可回圈出test0、test1...
db.insert("info",null,values);//呼叫insert方法
}
}
@Override
//點擊事件
public void onClick(View v) {
//得到內容提供者的決議物件
contentResolver = getContentResolver();
//uri路徑
Uri uri = Uri.parse("content://cn.luck.contentobserverdb/info");
//創建contentValues物件
ContentValues values = new ContentValues();
switch (v.getId()){
case R.id.add_btn:
values.put("name","add_test");
Uri newUri = contentResolver.insert(uri,values);
//提示
Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
break;
case R.id.update_btn:
//將info表中name為test1這條記錄更改為name是update_name
values.put("name","update_test");
int updateCount = contentResolver.update(uri,values,"name=?",new String[]{
"test2"
});
Toast.makeText(this,"成功更新"+updateCount+"行",Toast.LENGTH_SHORT).show();
break;
case R.id.delete_btn:
int deleteCount = contentResolver.delete(uri,"name=?",new String[]{
"test0"
});
Toast.makeText(this,"成功洗掉了"+deleteCount+"行",Toast.LENGTH_SHORT).show();
break;
case R.id.select_btn:
//集合
List<Map<String,String>> data = new ArrayList<>();
//回傳一個指向結果的游標
Cursor cursor = contentResolver.query(uri,new String[]{"_id","name"},
null,null,null);
while (cursor.moveToNext()){
Map<String,String> map = new HashMap<>();
map.put("_id",cursor.getString(0));
map.put("name",cursor.getString(1));
data.add(map);//添加到集合中
}
cursor.close();//關閉游標
Toast.makeText(this,"查詢成功",Toast.LENGTH_SHORT).show();
Log.i("查詢操作","查詢到的結果為:"+data.toString());
break;
}
}
}
3、效果展示

4、新建一個模塊,用于監測資料變化情況

結果如下:

三、補充
1、Android中的Uri詳解
2、Android中visibility屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/253130.html
標籤:其他
上一篇:1、【Vue上傳檔案】當介面Content-Type為multipart/form-data時,如何上傳檔案到后端
