Android - Get Contact Photo from phone number

后端 未结 6 1034
失恋的感觉
失恋的感觉 2020-12-15 19:45

how can I get contact photo from a contact\'s address (phone number)?

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 20:24

    public static Bitmap retrieveContactPhoto(Context context, String number) {
            ContentResolver contentResolver = context.getContentResolver();
            String contactId = null;
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    
            String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID};
    
            Cursor cursor =
                    contentResolver.query(
                            uri,
                            projection,
                            null,
                            null,
                            null);
    
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
                }
                cursor.close();
            }
    
            Bitmap photo = BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.default_image);
    
            try {
                if(contactId != null) {
                    InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                        ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(contactId)));
    
                    if (inputStream != null) {
                        photo = BitmapFactory.decodeStream(inputStream);
                    }
    
                    assert inputStream != null;
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return photo;
        }
    

提交回复
热议问题