要搜索特定号码的通话记录,可以使用以下代码示例:
public ArrayList searchCallLogs(Context context, String phoneNumber) {
ArrayList callLogs = new ArrayList<>();
// 获取通话记录的URI
Uri callUri = CallLog.Calls.CONTENT_URI;
// 定义要查询的字段
String[] projection = new String[]{
CallLog.Calls.NUMBER,
CallLog.Calls.DATE,
CallLog.Calls.DURATION,
CallLog.Calls.TYPE
};
// 设置查询条件
String selection = CallLog.Calls.NUMBER + " = ?";
String[] selectionArgs = new String[]{ phoneNumber };
// 查询通话记录
Cursor cursor = context.getContentResolver().query(
callUri,
projection,
selection,
selectionArgs,
CallLog.Calls.DATE + " DESC"
);
// 遍历查询结果
if (cursor != null && cursor.moveToFirst()) {
do {
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
String date = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
String duration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
String type = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE));
// 将通话记录添加到列表中
callLogs.add("Number: " + number + ", Date: " + date + ", Duration: " + duration + ", Type: " + type);
} while (cursor.moveToNext());
cursor.close();
}
return callLogs;
}
要使用上述代码示例,可以在Android应用的活动或片段中调用searchCallLogs
方法,并传入要搜索的电话号码。该方法将返回一个包含匹配的通话记录的字符串列表。请确保在使用此代码之前已经获取了通话记录的读取权限。
示例用法:
ArrayList callLogs = searchCallLogs(getApplicationContext(), "9876543210");
for (String callLog : callLogs) {
Log.d("Call Log", callLog);
}
这将打印出与电话号码"9876543210"相关的通话记录。