在Android编程中,获取CallLogs中的联系人姓名时,可能会遇到显示的是缓存的姓名而不是最新的更改后的姓名的问题。这是因为Android系统为了提高性能和减少对数据库的频繁访问,会对一些数据如联系人姓名等进行缓存。
要获取更改后的联系人姓名而不是缓存的姓名,可以通过以下步骤实现:
以下是一个示例代码,展示了如何实现这一过程:
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;
public String getContactNameFromCallLog(Context context, String phoneNumber) {
String contactName = null;
ContentResolver contentResolver = context.getContentResolver();
// Step 1: Query CallLogs to get the contact ID
Uri callLogUri = CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME, CallLog.Calls.CONTACT_ID};
Cursor callLogCursor = contentResolver.query(callLogUri, projection, CallLog.Calls.NUMBER + "=?", new String[]{phoneNumber}, null);
if (callLogCursor != null && callLogCursor.moveToFirst()) {
String contactId = callLogCursor.getString(callLogCursor.getColumnIndex(CallLog.Calls.CONTACT_ID));
// Step 2: Query Contacts database using the contact ID to get the latest name
if (contactId != null) {
Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
String selection = ContactsContract.Contacts._ID + "=?";
Cursor contactCursor = contentResolver.query(contactUri, null, selection, new String[]{contactId}, null);
if (contactCursor != null && contactCursor.moveToFirst()) {
contactName = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactCursor.close();
}
}
callLogCursor.close();
}
return contactName;
}
READ_CALL_LOG
和READ_CONTACTS
)在AndroidManifest.xml中声明,并且在运行时请求这些权限。通过这种方式,可以有效解决在Android编程中遇到的CallLogs显示缓存联系人姓名的问题。
领取专属 10元无门槛券
手把手带您无忧上云