編輯:關於 Android 程式設計
Android 的通訊錄與簡訊是透過 ContentProvider 對開發者開放介面的,因此一切都得從 ContentResolver 下手。
這塊最容易翻車的地方在於表的 URI 特別容易混淆——raw_contacts、data、mimetype 幾張表彼此關聯,少寫一層就會拿到空結果。接下來幾篇,我會依序整理聯絡人取得、通話記錄取得、簡訊取得、簡訊詳情與簡訊發送。

對開發者而言,主要關注三張表:
raw_contacts:每一筆「原始聯絡人」,存放 _id。data:實際的資料內容,用 mimetype 欄位區分是姓名、電話還是其他。關鍵觀念:姓名和電話不是同一列的兩個欄位,而是 data 表中兩筆不同的記錄,靠 mimetype 區分。這也是為什麼取值時必須跑巢狀迴圈。
package cn.zxw.contact.domain;
/**
* 聯絡人
*/
public class ContactsInfo {
public int _id;
public String name;
public String phone;
public String email;
public ContactsInfo() {
super();
}
public ContactsInfo(int _id, String name, String phone, String email) {
super();
this._id = _id;
this.name = name;
this.phone = phone;
this.email = email;
}
@Override
public String toString() {
return "ContactsInfo [_id=" + _id + ", name=" + name
+ ", phone=" + phone + ", email=" + email + "]";
}
}
/**
* 取得聯絡人清單
*/
public static List<ContactsInfo> getContactsInfos(Context context) {
ContentResolver resolver = context.getContentResolver();
List<ContactsInfo> infos = new ArrayList<ContactsInfo>();
// 先取得所有 raw_contacts 的 _id
// 對應的 authority 是 ContactsContract.AUTHORITY(com.android.contacts)
// 讀取此內容提供者需要 READ_CONTACTS 權限
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Cursor cursor1 = resolver.query(uri, new String[] {"_id"}, null, null, null);
while (cursor1.moveToNext()) {
int _id = cursor1.getInt(0);
ContactsInfo info = new ContactsInfo();
info._id = _id;
// 再針對每個 _id 去 data 表撈實際內容
uri = Uri.parse("content://com.android.contacts/raw_contacts/"
+ _id + "/data");
Cursor cursor2 = resolver.query(uri,
new String[] {"data1", "mimetype"}, null, null, null);
while (cursor2.moveToNext()) {
String data1 = cursor2.getString(0);
String mimetype = cursor2.getString(1);
if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
info.phone = data1; // 號碼
} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
info.name = data1; // 姓名
}
}
cursor2.close();
infos.add(info);
}
cursor1.close();
return infos;
}
幾個實務提醒:
ContactsContract.CommonDataKinds.Phone 與 StructuredName 的常數,而不是硬寫 mimetype 字串。Google 已經幫你把這些常數定義好了,自己打字串容易出錯。ContactsContract.Contacts 的 has_phone_number 搭配一次查詢完成。useCursor 相關輔助,避免 Cursor 洩漏導致 CursorWindowAllocationException。/**
* 取得所有通話記錄
*/
public List<CallLogInfo> getCallLog(Context context) {
List<CallLogInfo> infos = new ArrayList<CallLogInfo>();
ContentResolver cr = context.getContentResolver();
Uri uri = CallLog.Calls.CONTENT_URI;
String[] projection = new String[] {
CallLog.Calls.NUMBER,
CallLog.Calls.DATE,
CallLog.Calls.TYPE
};
Cursor cursor = cr.query(uri, projection, null, null, null);
while (cursor.moveToNext()) {
String number = cursor.getString(0);
long date = cursor.getLong(1);
int type = cursor.getInt(2);
infos.add(new CallLogInfo(number, date, type));
}
cursor.close();
return infos;
}
package cn.zxw.contact;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import cn.zxw.contact.domain.ContactsInfo;
import cn.zxw.contact.utils.ContactsMsgUtils;
public class ContactsActivity extends Activity {
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_msg_calllog);
lv = (ListView) findViewById(R.id.lv);
List<ContactsInfo> infos =
ContactsMsgUtils.getContactsInfos(getApplicationContext());
lv.setAdapter(new MyAdapter(infos));
}
private class MyAdapter extends BaseAdapter {
private final List<ContactsInfo> infos;
MyAdapter(List<ContactsInfo> infos) {
this.infos = infos;
}
@Override
public int getCount() {
return infos.size();
}
@Override
public Object getItem(int position) {
return infos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(getApplicationContext(),
R.layout.contacts_list_item, null);
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
ContactsInfo info = infos.get(position);
tv_number.setText(info.phone);
tv_name.setText(info.name);
return view;
}
}
}
這段 Adapter 是教學用的寫法,每次 getView 都重新 inflate。正式專案請務必加上 ViewHolder 與 convertView 重用,否則聯絡人一多就會明顯掉幀。
<uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_CALL_LOG" />
從 Android 6.0(API 23)開始,這兩個都是危險權限,必須在執行期以 requestPermissions() 動態向使用者請求,並處理好「使用者拒絕」與「使用者勾選不再詢問」兩種情況。只在 Manifest 宣告是不夠的。
另外從 Android 10 開始,READ_CALL_LOG 屬於受限制權限,上架 Google Play 需要提交用途說明並通過審核;部分中國大陸的應用商店也有各自的規範。設計功能前先確認政策,能省下不少後續麻煩。
下一篇我們來談通話記錄的取得與呈現。
Android ViewPager 學習筆記:Fragment 頁面與資料載入
ViewPager 常用於實作可左右滑動的頁面切換效果。搭配 Fragment 與 PagerAdapter,可以輕鬆建立多頁式介面。 基本架構 在 MainActivi
Android 開發環境變量配置圖文教學
無論使用 ADT 還是 Android Studio 開發,都需要先下載 JDK(官網 https://www.oracle.com/index.html)。安裝完成後,
Android 版面配置釐清:gravity 與 layout_gravity 的差異
在 Android 版面配置中,gravity 與 layout_gravity 經常被混淆。兩者都與對齊有關,但作用對象不同。理解差異後,可以更精準地控制介面排列。 g
Android 學習筆記:Switch 開關控件的使用案例
Switch 是一個帶有開關效果的控件,常用來表示某個功能的開啟或關閉狀態。以下透過一個簡單範例說明它的布局與事件處理。 布局程式碼 控制程式碼