【Android通話記錄】仿小米通話
阿新 • • 發佈:2019-02-07
首先讀取通話記錄許可權:
<uses-permission android:name="android.permission.READ_CALL_LOG"/>
和上一篇一樣,先判斷許可權是否獲取,然後再進行相關操作。
主要程式碼:
private void initRecord() {
Uri uri = CallLog.Calls.CONTENT_URI;
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ _CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.READ_CALL_LOG}, READ_CONTACTS_PERMISSIONS_REQUEST);
return;
}
Cursor cursor = getActivity().getContentResolver ().query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
do {
RecordEntity recordEntity = new RecordEntity();
//號碼
recordEntity.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
//呼叫型別
recordEntity.setType (Integer.parseInt(cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE))));
SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE))));
//呼叫時間
recordEntity.setlDate(sfd.format(date));
//聯絡人
recordEntity.setName(cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME)));
Log.e("---------->", cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME))+"");
//通話時間,單位:s
recordEntity.setDuration(cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION)));
recordEntityList.add(recordEntity);
} while (cursor.moveToNext());
}
getActivity().startManagingCursor(cursor);//cursor的生命週期託管給activity
//設定列表資料和浮動header
final LinearLayoutManager layoutManager = new
LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
RecordAdapter recordAdapter = new RecordAdapter();
recyclerView.setAdapter(recordAdapter);
// Add decoration for dividers between list items
recyclerView.addItemDecoration(new DividerDecoration(getActivity()));
}