Android平台開放程度的確很厲害,你幾乎可以調用任何底層的介面,甚至攔截到簡訊或者呼入電話。這些是J2ME平台無法比擬的。本文介紹一下如何訪問android的通話記錄。
android平台上的通話記錄是以Content Provider的形式儲存在手機上的,因此你需要使用ContentResolver來查詢通話記錄,返回Cursor介面。如下所示:
package com.me;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
public class CallLogActivity extends ListActivity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.main);
Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor,
new String[] { CallLog.Calls.NUMBER },
new int[] { android.R.id.text1 });
setListAdapter(adapter);
}
}
獲得了Cursor之後便可以構建一個Adapter然後調用setListAdapter()來把通話記錄顯示在螢幕上。CallLog類中定義了Calls類,在android中可以看到大量的內部類的設計。Calls定義了很多常量,方便你來訪問通話記錄,主要包括兩個URI和多個欄位定義,比如我們在這裡用到的NUMBER。更多內容請參考Andorid doc。
下面是/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No Notes!"/>
</LinearLayout>