1

我使用此代码从联系人的电话号码中设置图片。从电话号码我得到一个联系人 ID,从这个 ID 我可以得到一个照片 URL。

我试图在 imageview 中设置图片: mPhotoView.setImageURI(uri); 但它不会工作。我已经调试并且 URL 不等于 null。

该 URL 包含以下内容:content://com.android.contacts/contacts/502/photo

有谁知道如何解决这一问题?

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImageView mPhotoView = (ImageView) findViewById(R.id.imageView1);

    Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(YOUR_PHONENUMBER))); //Set a number for yourself!
    if (uri != null) {
            mPhotoView.setImageURI(uri);
    } else {
            mPhotoView.setImageResource(R.drawable.ic_launcher);
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public String fetchContactIdFromPhoneNumber(String phoneNumber) {
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phoneNumber));
    Cursor cursor = this.getContentResolver().query(uri,
            new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
            null, null, null);

    String contactId = "";

    if (cursor.moveToFirst()) {
        do {
            contactId = cursor.getString(cursor
                    .getColumnIndex(PhoneLookup._ID));
        } while (cursor.moveToNext());
    }

    return contactId;
}

public Uri getPhotoUri(long contactId) {
    ContentResolver contentResolver = getContentResolver();

    try {
        Cursor cursor = contentResolver
                .query(ContactsContract.Data.CONTENT_URI,
                        null,
                        ContactsContract.Data.CONTACT_ID
                                + "="
                                + contactId
                                + " AND "

                                + ContactsContract.Data.MIMETYPE
                                + "='"
                                + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                                + "'", null, null);

        if (cursor != null) {
            if (!cursor.moveToFirst()) {
                return null; // no photo
            }
        } else {
            return null; // error in cursor process
        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    Uri person = ContentUris.withAppendedId(
            ContactsContract.Contacts.CONTENT_URI, contactId);
    return Uri.withAppendedPath(person,
            ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}

}

4

0 回答 0