編輯:關於 Android 程式設計
在上一篇我們已經完成了聯繫人資料的讀取,本篇接著談談如何取得並展示手機的通話記錄。整體思路與聯繫人類似,透過系統的 CallLog 內容提供者查詢資料,再用自訂的 Adapter 呈現在列表上。

如需完整範例程式碼,可至原作者的 CSDN 下載頁取得。
主列表使用 ListView 承載通話紀錄,並以黑色為底:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/contact_record_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<ListView
android:id="@+id/call_log_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:cacheColorHint="#000000"
android:fadingEdge="none"
android:scrollingCache="false"
android:visibility="visible" />
</RelativeLayout>
單行項目則由來電類型圖示、名稱、號碼、時間與撥號按鈕組成:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/call_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:background="@drawable/ic_calllog_outgoing_nomal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/call_type"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#ffffff" />
<TextView
android:id="@+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#cccccc" />
</LinearLayout>
<TextView
android:id="@+id/call_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:background="@drawable/ic_calllog_call_btn" />
<ImageView
android:id="@+id/fg"
android:layout_width="wrap_content"
android:layout_height="75dip"
android:layout_toLeftOf="@+id/call_btn"
android:background="@drawable/black_bg" />
<TextView
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="@+id/fg"
android:textColor="#ffffff" />
</RelativeLayout>
用一個簡單的 JavaBean 封裝每一筆通話紀錄:
package com.suntek.contact.model;
/**
* 通話記錄實體類
*/
public class CallLogBean {
private int id;
private String name; // 名稱
private String number; // 號碼
private String date; // 日期
private int type; // 來電:1,撥出:2,未接:3
private int count; // 通話次數
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getNumber() { return number; }
public void setNumber(String number) { this.number = number; }
public String getDate() { return date; }
public void setDate(String date) { this.date = date; }
public int getType() { return type; }
public void setType(int type) { this.type = type; }
public int getCount() { return count; }
public void setCount(int count) { this.count = count; }
}
DialAdapter 負責把資料綁定到列表,並透過 ViewHolder 做效能優化,同時為撥號按鈕掛上點擊事件:
package com.suntek.contact.adapter;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.suntek.contact.R;
import com.suntek.contact.model.CallLogBean;
/**
* 通話記錄適配器
*/
public class DialAdapter extends BaseAdapter {
private Context ctx;
private List<CallLogBean> callLogs;
private LayoutInflater inflater;
public DialAdapter(Context context, List<CallLogBean> callLogs) {
this.ctx = context;
this.callLogs = callLogs;
this.inflater = LayoutInflater.from(context);
}
@Override public int getCount() { return callLogs.size(); }
@Override public Object getItem(int position) { return callLogs.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.contact_record_list_item, null);
holder = new ViewHolder();
holder.call_type = (ImageView) convertView.findViewById(R.id.call_type);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.number = (TextView) convertView.findViewById(R.id.number);
holder.time = (TextView) convertView.findViewById(R.id.time);
holder.call_btn = (TextView) convertView.findViewById(R.id.call_btn);
convertView.setTag(holder); // 快取
} else {
holder = (ViewHolder) convertView.getTag();
}
CallLogBean callLog = callLogs.get(position);
switch (callLog.getType()) {
case 1:
holder.call_type.setBackgroundResource(R.drawable.ic_calllog_outgoing_nomal);
break;
case 2:
holder.call_type.setBackgroundResource(R.drawable.ic_calllog_incomming_normal);
break;
case 3:
holder.call_type.setBackgroundResource(R.drawable.ic_calllog_missed_normal);
break;
}
holder.name.setText(callLog.getName());
holder.number.setText(callLog.getNumber());
holder.time.setText(callLog.getDate());
addViewListener(holder.call_btn, callLog, position);
return convertView;
}
private static class ViewHolder {
ImageView call_type;
TextView name;
TextView number;
TextView time;
TextView call_btn;
}
private void addViewListener(View view, final CallLogBean callLog, final int position) {
view.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
Uri uri = Uri.parse("tel:" + callLog.getNumber());
Intent intent = new Intent(Intent.ACTION_CALL, uri);
ctx.startActivity(intent);
}
});
}
}
關鍵在於使用 AsyncQueryHandler 異步行查詢 CallLog.Calls,避免阻塞主執行緒:
package com.suntek.contact;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.ListView;
import com.suntek.contact.adapter.DialAdapter;
import com.suntek.contact.model.CallLogBean;
/**
* 通話記錄列表
*/
public class ContactRecordListActivity extends Activity {
private ListView callLogListView;
private AsyncQueryHandler asyncQuery;
private DialAdapter adapter;
private List<CallLogBean> callLogs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_record_list_view);
callLogListView = (ListView) findViewById(R.id.call_log_list);
asyncQuery = new MyAsyncQueryHandler(getContentResolver());
init();
}
private void init() {
Uri uri = android.provider.CallLog.Calls.CONTENT_URI;
String[] projection = {
CallLog.Calls.DATE, // 日期
CallLog.Calls.NUMBER, // 號碼
CallLog.Calls.TYPE, // 類型
CallLog.Calls.CACHED_NAME, // 名字
CallLog.Calls._ID // id
};
asyncQuery.startQuery(0, null, uri, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
}
private class MyAsyncQueryHandler extends AsyncQueryHandler {
public MyAsyncQueryHandler(ContentResolver cr) { super(cr); }
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
callLogs = new ArrayList<CallLogBean>();
SimpleDateFormat sfd = new SimpleDateFormat("MM-dd hh:mm");
Date date;
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
date = new Date(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
String cachedName = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
int id = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));
CallLogBean callLogBean = new CallLogBean();
callLogBean.setId(id);
callLogBean.setNumber(number);
callLogBean.setName(cachedName);
if (null == cachedName || "".equals(cachedName)) {
callLogBean.setName(number);
}
callLogBean.setType(type);
callLogBean.setDate(sfd.format(date));
callLogs.add(callLogBean);
}
if (callLogs.size() > 0) {
setAdapter(callLogs);
}
}
super.onQueryComplete(token, cookie, cursor);
}
}
private void setAdapter(List<CallLogBean> callLogs) {
adapter = new DialAdapter(this, callLogs);
callLogListView.setAdapter(adapter);
}
}
整段邏輯離不開三個核心類別:Uri 作為通用資源標識用來定位資料來源;AsyncQueryHandler 是 Android 提供的異步資料庫操作類,透過它的 startQuery 發起查詢,並在 onQueryComplete 回呼中取得 Cursor 游標;最後藉由游標逐一讀取各欄位的值。此外別忘了在清單檔加入 READ_CALL_LOG 權限,否則會讀不到資料。
Android 快速實作一個通用 EmptyView 空視圖
好的 App 應該具備良好的互動,最好能貼心滿足使用者需求,而人性化的提醒正是其中一環。我們常在某些 App 看到這樣的場景:當內容載入失敗或抓取資料失敗時,畫面會切換成
Android 整合微信支付與支付寶:完整流程與安全實務提醒
最近比較空閒,加上公司專案換了後台,於是著手研究微信支付與支付寶的整合,把學習過程記錄下來,以後回頭查也方便。 零、先談安全,再談代碼 整合行動支付前,必須先取得幾組憑
自訂 TextView 跑馬燈:可控制啟動、停止與速度
為什麼要自己寫 Android 內建的跑馬燈效果不好控制:速度無法調整,不能即時停止與啟動,還得依賴焦點,實在麻煩。由於專案需要一個可控性高的版本,於是決定自訂一個 Te
深入解析 Android View 的繪製原理
一、初識 ViewRoot 與 DecorView ViewRoot 對應的實作類是 ViewRootImpl,它扮演著連接 WindowManager 與 DecorV