Get contact name given a phone number in Android

前端 未结 4 422
礼貌的吻别
礼貌的吻别 2020-12-05 12:16

I am trying to retrieve contact names given the contact phone number. I made a function that should work in all API versions, by I can\'t make it work in 1.6 and I can\'t se

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 12:37

    Use reflections instead of comparing sdk version.

    public String getContactName(final String phoneNumber) 
    {  
        Uri uri;
        String[] projection;
        mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
        projection = new String[] { android.provider.Contacts.People.NAME }; 
        try {
            Class c =Class.forName("android.provider.ContactsContract$PhoneLookup");
            mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
            projection = new String[] { "display_name" };
        } 
        catch (Exception e) {
        }
    
    
        uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber)); 
        Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 
    
        String contactName = "";
    
        if (cursor.moveToFirst()) 
        { 
            contactName = cursor.getString(0);
        } 
    
        cursor.close();
        cursor = null;
    
        return contactName; 
    }
    

提交回复
热议问题