編輯:關於 Android 程式設計
數據庫解決的是「程式訪問自己的資料」,而內容提供器(ContentProvider)解決的是「跨程式共享資料」。它的操作依然離不開增刪改查,只是訪問主體從本應用換成了其他應用。
Android 中每個應用的數據庫是私有的,默認不允許其他應用訪問。內容提供者的職責就是在「被訪問方」與「訪問方」之間搭一座橋:提供方繼承 ContentProvider、重寫增刪改查方法並在其中操作自己的數據庫;訪問方則透過 ContentResolver 發起調用。
第一步:繼承 ContentProvider 並重寫方法。
@Override
public Uri insert(Uri uri, ContentValues values) {
db.insert("person", null, values);
return uri;
}
第二步:在清單檔中註冊,authorities 是它的「主機名」,必填。
<provider
android:name="com.it.contentprovider.PersonProvider"
android:authorities="com.it.person"
android:exported="true" />
第三步:在其他應用中透過 ContentResolver 訪問。
public void click(View v) {
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
cv.put("name", "小方");
cv.put("phone", 138856);
cv.put("money", 3000);
// content:// 後面接的就是 authorities
cr.insert(Uri.parse("content://com.it.person"), cv);
}
當一個 ContentProvider 需要對外暴露多張表時,就要靠 UriMatcher 判斷當前的 uri 命中哪一條規則。
// 註冊匹配規則
um.addURI("com.itheima.person", "person", PERSON_CODE);
um.addURI("com.itheima.person", "company", COMPANY_CODE);
// # 可代表任意數字
um.addURI("com.itheima.person", "person/#", QUERY_ONE_PERSON_CODE);
// 依匹配結果操作不同的表
@Override
public Uri insert(Uri uri, ContentValues values) {
if (um.match(uri) == PERSON_CODE) {
db.insert("person", null, values);
} else if (um.match(uri) == COMPANY_CODE) {
db.insert("company", null, values);
} else {
throw new IllegalArgumentException("不匹配");
}
return uri;
}
// 提取路徑末尾的數字 id
int id = (int) ContentUris.parseId(uri);
短信由系統的內容提供者對外開放,只需要關注 sms 表,核心欄位有四個:
讀取短信:先查源碼確認 authorities 與路徑,再發起查詢。
ContentResolver cr = getContentResolver();
Cursor c = cr.query(Uri.parse("content://sms"),
new String[]{"body", "date", "address", "type"}, null, null, null);
while (c.moveToNext()) {
String body = c.getString(0);
String date = c.getString(1);
String address = c.getString(2);
String type = c.getString(3);
System.out.println(body + ";" + date + ";" + address + ";" + type);
}
寫入短信:
ContentResolver cr = getContentResolver();
ContentValues cv = new ContentValues();
cv.put("body", "您尾號為 XXXX 的儲蓄卡收到轉賬 1,000,000 元");
cv.put("address", 95555);
cv.put("type", 1);
cv.put("date", System.currentTimeMillis());
cr.insert(Uri.parse("content://sms"), cv);
無論讀取還是插入系統短信,都需要在清單檔中註冊相應的權限。
聯絡人的存儲模型是「主表 + 明細表」:
讀取聯絡人需要兩步查詢:
// 1. 先取聯絡人 id
Cursor cursor = cr.query(
Uri.parse("content://com.android.contacts/raw_contacts"),
new String[]{"contact_id"}, null, null, null);
// 2. 再拿 id 去 data 表查明細
Cursor c = cr.query(Uri.parse("content://com.android.contacts/data"),
new String[]{"data1", "mimetype"},
"raw_contact_id = ?", new String[]{contactId}, null);
// 3. 依 mimetype 判斷資訊類型
while (c.moveToNext()) {
String data1 = c.getString(0);
String mimetype = c.getString(1);
if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {
contact.setEmail(data1);
} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
contact.setName(data1);
} else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
contact.setPhone(data1);
}
}
插入聯絡人的思路 likewise 是兩段式:先確定新的 contact_id 並插入 raw_contacts,再往 data 表逐條寫入明細。
// 1. 建立聯絡人主記錄
cv.put("contact_id", _id);
cr.insert(Uri.parse("content://com.android.contacts/raw_contacts"), cv);
// 2. 寫入姓名
cv = new ContentValues();
cv.put("data1", "趙六");
cv.put("mimetype", "vnd.android.cursor.item/name");
cv.put("raw_contact_id", _id);
cr.insert(Uri.parse("content://com.android.contacts/data"), cv);
// 3. 寫入電話
cv = new ContentValues();
cv.put("data1", "1596874");
cv.put("mimetype", "vnd.android.cursor.item/phone_v2");
cv.put("raw_contact_id", _id);
cr.insert(Uri.parse("content://com.android.contacts/data"), cv);
輪詢查詢顯然不是好主意。ContentProvider 在資料變更時會發出通知,我們只要在對應的 uri 上註冊一個 ContentObserver,就能被動收到回調。
// 註冊觀察者
cr.registerContentObserver(Uri.parse("content://sms"), true, new MyObserver(new Handler()));
class MyObserver extends ContentObserver {
public MyObserver(Handler handler) {
super(handler);
}
// 資料變更時回調
@Override
public void onChange(boolean selfChange) {
// 在這裡刷新介面
}
}
// 提供方發出通知:所有註冊在該 uri 上的觀察者都會收到
ContentResolver cr = getContext().getContentResolver();
cr.notifyChange(uri, null);
這一章的知識點可以串成一條線:自訂 ContentProvider 把私有數據庫對外暴露 → 用 authorities 作為訪問入口 → 用 UriMatcher 在同一入口下路由到不同表 → 訪問方一律透過 ContentResolver 以 uri 為中心做增刪改查 → 需要感知變化時註冊 ContentObserver 接收 notifyChange 通知。
而系統短信與聯絡人,本質上就是「別人已經寫好的 ContentProvider」,我們只是換成訪問方角色,並記得申辦對應的讀寫權限即可。
360 手機衛士開啟來電顯示歸屬地:圖解設定流程
想知道來電是哪個地區打來的,用 360 手機衛士開啟歸屬地顯示就能做到。設定路徑並不深,照下面三步走完即可。 1. 安裝並打開 360 手機衛士,切換到「隱私保護」,點擊
Android 官方文檔精讀:App Components 之 Activities
Activity 是 Android 四大組件之首。本文將圍繞 Activity 的含義、創建、啟動、銷毀以及生命周期等方面展開介紹。 Activity 是什麼 Act
Android SQLite 資料庫操作:兩種寫法完整對照實作
幾乎每支 Android 應用都會碰到本機資料庫,而 SQLite 的操作方式其實有兩條路可以走:直接寫 SQL 字串,或是使用 Android 提供的 ContentV
Realm 行動資料庫入門:跨平台 ORM、效能優勢與學習重點
Realm 是什麼Realm 是一套跨平台行動資料庫引擎,支援 iOS、OS X 與 Android。它並非建立在 SQLite 之上的 ORM,而是使用自有核心引擎,目