android - 通过 Intent with Image (Photo) 插入联系人 (ContactsContract)

标签 android android-intent android-contentprovider android-image contactscontract

有很多问答帖,但没有一个提供真正的答案,或者我找不到。

为了确保您的安全,我在询问之前进行了搜索:

那么有没有人知道如何使用 Intent(如示例代码中所示)并插入保存在 Bitmap 中的照片?

我现在使用的示例代码为用户启动对话 Intent ,让他在保存之前插入或取消并可能编辑字段:

// PrivateContactClass c;
// Bitmap photo;
Intent inOrUp = new Intent(ContactsContract.Intents.Insert.ACTION, ContactsContract.Contacts.CONTENT_URI);
inOrUp.setType(ContactsContract.Contacts.CONTENT_TYPE);
inOrUp.putExtra(ContactsContract.Intents.Insert.NAME, ModelUtils.formatName(c));
inOrUp.putExtra(ContactsContract.Intents.Insert.PHONE, getPrimaryPhone());
inOrUp.putExtra(ContactsContract.Intents.Insert.TERTIARY_PHONE, c.getMobile());
inOrUp.putExtra(ContactsContract.Intents.Insert.EMAIL, c.getMail());
inOrUp.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, c.getFunction());
inOrUp.putExtra(ContactsContract.Intents.Insert.NOTES, getSummary());
inOrUp.putExtra(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
startActivity(inOrUp);

多亏了 Julien 的回答,我找到了解决方案

不能仅使用 Intent,因为我怀疑我们能否传递 Data ContentProvider 保存的图像 ID,或者直接在 Intent 中传递 Bitmap。

从上面的代码扩展

使用带有常量请求代码的 startActivityForResult

// must be declared in class-context
private static final int CONTACT_SAVE_INTENT_REQUEST = 1;
...
startActivityForResult(inOrUp,CONTACT_SAVE_INTENT_REQUEST);

添加 Intent 启动的 Activity 的处理结果

@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    switch (requestCode) {
    case RESULT_INSERT_CONTACT:
        if (resultCode == RESULT_OK) {
            trySetPhoto();
        }
        break;
    }
}

添加设置照片的方法

public boolean setDisplayPhotoByRawContactId(long rawContactId, Bitmap bmp) {
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
     byte[] byteArray = stream.toByteArray();
     Uri pictureUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI, 
             rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
     try {
         AssetFileDescriptor afd = getContentResolver().openAssetFileDescriptor(pictureUri, "rw");
         OutputStream os = afd.createOutputStream();
         os.write(byteArray);
         os.close();
         afd.close();
         return true;
     } catch (IOException e) {
         e.printStackTrace();
     }
     return false;
 }

添加搜索联系人和添加联系人照片的方法

private void trySetPhoto() {
    // Everything is covered in try-catch, as this method can fail on 
    // low-memory or few NPE
    try {
        // We must have an phone identifier by which we search for
        // format of phone number is not relevant, as ContentProvider will
        // normalize it automatically
        if (c.getMobile() != null) {
            Uri lookup = Uri.withAppendedPath(
                    ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(c.getMobile()));
            Cursor c = getContentResolver().query(lookup, null, null, null,
                    null);
            // Remember cursor can be null in some cases
            if (c != null) {
                // we can obtain bitmap just once
                Bitmap photo_bitmap = getPhotoBitmap();
                c.moveToFirst();
                // if there are multiple raw contacts, we want to set the photo for all of them
                while (c.moveToNext()) {
                    setDisplayPhotoByRawContactId(
                            c.getLong(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID)),
                            photo_bitmap);
                }
                // remember to clean up after using cursor
                c.close();
            }
        }
    } catch (Exception e) {
        // Logging procedures
    } catch (Error e) {
        // Logging procedures
    }
}

最佳答案

Bitmap bit = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); // your image

ArrayList<ContentValues> data = new ArrayList<ContentValues>();

ContentValues row = new ContentValues();
row.put(Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
row.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bitmapToByteArray(bit));
data.add(row);

Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.CONTENT_URI);
intent.putParcelableArrayListExtra(Insert.DATA, data);

关于android - 通过 Intent with Image (Photo) 插入联系人 (ContactsContract),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026292/

相关文章:

java - android 首选项问题和需要的帮助

android - 如何在没有振荡运动的情况下平滑地围绕图像中心旋转位图

android - 如何直接从我的 Android 应用程序打开 Google Play 商店?

android - ContentProvider 实例化失败 - NullPointerException

来自内部存储的 Android Intent.ACTION_SEND 和 Content Provider

Javascript touchend 事件不会在 Android 上触发

Android:定义 onDraw Canvas 大小

Android 服务将一个 Activity 的多个实例放入历史记录中

android - 无法在 ArrayAdapter 中将 Intent 添加到 Google Maps

android - 使用 ContentProvider 或 Intent 从应用程序向其他应用程序发送数据?