首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过意图与图像插入联系人(ContactsContract) (照片)

通过意图与图像插入联系人(ContactsContract) (照片)
EN

Stack Overflow用户
提问于 2013-02-22 14:22:54
回答 4查看 7.1K关注 0票数 13

Q&A线程很多,但它们都没有提供真正的答案,或者我找不到它。

为了确保你,我在问:

  • http://thinkandroid.wordpress.com/2009/12/30/handling-contact-photos-all-api-levels/ (不使用意图)

那么,有谁知道如何使用意图(如示例代码)并插入位图中的照片呢?

我现在确实使用了示例代码来启动对话框,以便用户在保存之前允许他插入或取消并可能编辑字段:

代码语言:javascript
复制
// 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);

我找到了解决办法,多亏了朱利安的回答

不只是使用意图,因为我怀疑我们是否能够传递由数据ContentProvider保存的图像的ID,或者在意向中直接传递位图。

扩展自上面的代码

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

代码语言:javascript
复制
// must be declared in class-context
private static final int CONTACT_SAVE_INTENT_REQUEST = 1;
...
startActivityForResult(inOrUp,CONTACT_SAVE_INTENT_REQUEST);

添加根据意图启动的活动的处理结果。

代码语言:javascript
复制
@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;
    }
}

添加方法设置照片

代码语言:javascript
复制
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;
 }

添加方法以搜索联系人并添加联系人照片

代码语言:javascript
复制
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
    }
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-05-29 01:13:40

代码语言:javascript
复制
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);
票数 14
EN

Stack Overflow用户

发布于 2013-02-26 09:25:11

为了帮助您,我找到了原始文档:http://java.llp2.dcc.ufmg.br/apiminer/docs/reference/android/provider/ContactsContract.RawContacts.DisplayPhoto.html

阅读以下内容:http://java.llp2.dcc.ufmg.br/apiminer/docs/reference/android/provider/ContactsContract.RawContacts.html

对我来说,一个简单的解决方案是,如果您的代码可以调用:

代码语言:javascript
复制
startActivityForResult(inOrUp, CODE_INSERT_CONTACT);

然后在"onActivityResult“中调用”setDisplayPhotoByRawContactId“:

代码语言:javascript
复制
    /** @return true if picture was changed false otherwise. */
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;
 }

通常,这段代码来自API的第14版。我不得不对这个话题做研究。

您可以获得rawContactId,如文档中所示:

代码语言:javascript
复制
Uri rawContactUri = RawContacts.URI.buildUpon()
      .appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName)
      .appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType)
      .build();
long rawContactId = ContentUris.parseId(rawContactUri);

我不确定但这些文件会对你有帮助的。对不起我的英语。

票数 4
EN

Stack Overflow用户

发布于 2014-06-09 16:31:24

被接受的答案不符合问题的要求。

请参阅@yeo100 100回答,它使用ContactsContract.Intents.Insert.DATA (文档 -有点模糊,很难找到:/),因为联系人照片保存在数据表中的特定类型:

Data.MIMETYPE -> ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE

这对我来说很管用,而且更整洁,更容易管理。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15026292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档