Android开发之获取手机通话记录

时间:2022-06-08 22:55:09

Android手机想要获取通话记录,可以使用CallLog。

java文件关键部分内容:

private ContentResolver cr;

private Cursor cursor;

private String LOG = "MobileCalls";

String str = "通话记录:\n";

public void setContenResolver() {

int i = 0;

setCr(context.getContentResolver());

setCursor(getCr().query(CallLog.Calls.CONTENT_URI,// 使用系统URI,取得通话记录

new String[] { CallLog.Calls.NUMBER,// 电话号码

CallLog.Calls.CACHED_NAME,// 联系人

CallLog.Calls.TYPE,// 通话类型

CallLog.Calls.DATE,// 通话时间

CallLog.Calls.DURATION// 通话时长

}, null, null, CallLog.Calls.DEFAULT_SORT_ORDER));


// 遍历每条通话记录

for (cursor.moveToFirst(); !cursor.isAfterLast() && i < 100;cursor

.moveToNext()) {

String strNumber = cursor.getString(0); // 呼叫号码

String strName = cursor.getString(1); // 联系人姓名

int type =cursor.getInt(2);

String str_type = "";

if (type == CallLog.Calls.INCOMING_TYPE) {

str_type = "呼入";

} elseif (type == CallLog.Calls.OUTGOING_TYPE) {

str_type = "呼出";

} elseif (type == CallLog.Calls.MISSED_TYPE) {

str_type = "未接";

}

long duration =cursor.getLong(4);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date = new Date(Long.parseLong(cursor.getString(3)));

String time = sdf.format(date);

Log.i(LOG,"\n类型:" + str_type + "\n称呼:" + strName +"\n号码:"

+ strNumber +"\n通话时长:" + duration + "秒" + "\n时间:" + time

+"\n---------------------\n");

i++;

}

}

当然,需要在MainFest.xml中申请以下权限:

<uses-permissionandroid:name="android.permission.READ_CALL_LOG"/> <!-- 获取通话记录所需的权限 -->

然后你就可以查看手机通话记录啦!