本文主要实现类似iPhone通话记录效果,即相邻通话如果通话号码相同、通话类型(呼入、呼出、未接)相同、间隔时间(某一阈值范围内),则将其归为一条记录,否则,将其分别显示。首先获取通话记录必须添加一下权限:
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG"/>
然后通过一下代码获取通话记录:
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
然后须通过遍历通话记录,按照显示规则进行显示,在此需了解Cursor的相关知识:cursor.moveToFirst表示移动至当前记录的第一条,cursor.moveToNext表示当前记录的下一条记录,cursor.moveToPrevious表示当前记录的上一条记录,cursor.moveToLast表示当前记录的最后一条记录,一般moveToFirst和moveToNext、moveToPrevious和moveToLast配套使用。随后我们进行通话记录显示:
private void getCallRecord() {
SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, null);
int i=0;
if(cursor.moveToLast()){
String prenumber=cursor.getString(cursor.getColumnIndex(Calls.NUMBER));
int type = TypeDecision(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Calls.TYPE))));
Date date = new Date(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(Calls.DATE))));
String time = sfd.format(date);
String name = cursor.getString(cursor.getColumnIndexOrThrow(Calls.CACHED_NAME));
String duration = cursor.getString(cursor.getColumnIndexOrThrow(Calls.DURATION));
callrecords.add(new CallEntity(type, time, "0", prenumber, duration));
while(cursor.moveToPrevious()){
String numbers = cursor.getString(cursor.getColumnIndex(Calls.NUMBER));
int temptype = TypeDecision(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Calls.TYPE))));
Date tempdate = new Date(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(Calls.DATE))));
String temptime = sfd.format(tempdate);
String tempname = cursor.getString(cursor.getColumnIndexOrThrow(Calls.CACHED_NAME));
String tempduration = cursor.getString(cursor.getColumnIndexOrThrow(Calls.DURATION));
if(!prenumber.equals(numbers) || !temptime.equals(time) || (temptype != type)){
callrecords.add(new CallEntity(temptype, temptime, "0", numbers, tempduration));
prenumber=numbers;
time=temptime;
type=temptype;
}else{
time=temptime;
prenumber=numbers;
type=temptype;
}
}
}
}
随后需要建立一个适配器来显示相应的listview item,相信大家都会,网上也有很多资料可供大家参考,希望此篇文章对大家有所帮助,不对之处欢迎大家指正。