简体   繁体   English

如何通过联系人API在Android中设置照片

[英]How to set a photo in android via the contacts api

i'm new to developing android apps and I'm currently trying to do the following: Search all contacts' notes for a certain string (say: "E-Plus") and, if found, place a certain icon (say the E-Plus logo) as their contact photo. 我是开发Android应用程序的新手,我目前正在尝试执行以下操作:在所有联系人的笔记中搜索特定字符串(例如:“ E-Plus”),如果找到,则放置特定图标(例如E -Plus徽标)作为他们的联系照片。

I got it working using eclipse and the following test AVD: Platform: Android 2.3.3 API Level: 10 CPU/ABI: ARM (armeabi) 我使用eclipse和以下测试AVD使其正常工作:平台:Android 2.3.3 API级别:10 CPU / ABI:ARM(armeabi)

Now, when i copy the *.apk file generated from eclipse to my Samsung Galaxy S2, the app only works partly. 现在,当我将从eclipse生成的* .apk文件复制到我的Samsung Galaxy S2时,该应用程序只能部分运行。 I added a line to display a toast after searching all contacts, that tells me how many contacts have been found with the specific string. 我在搜索所有联系人之后添加了一行以显示祝酒词,告诉我在特定字符串中找到了多少个联系人。 This number is correct, when i execute the app on my actual Galaxy S2. 当我在实际的Galaxy S2上执行应用程序时,此数字是正确的。

But in contrary to the testing environment, the app doesnt set the photo afterwards. 但是与测试环境相反,该应用程序之后不会设置照片。 The app also doesn't crash. 该应用程序也不会崩溃。 Then i thought, setting a photo might be too difficult as a first approach, so i also tried adding a phone number - same result. 然后我想,设置照片作为第一种方法可能太困难了,所以我也尝试添加电话号码-同样的结果。 The phone number is added correctly in the testing environment, but not on my actual phone. 电话号码已在测试环境中正确添加,但未在我的实际电话中添加。

I tried both a google contact on my phone and a normal phonebook entry contact to have the certain note in its details. 我尝试通过手机上的google联系人和普通电话簿录入联系人在其详细信息中添加特定注释。 Both were found correctly by the app (that is note was read and string was found) but neither of them had the photo or phone number set after running the app. 应用程序正确找到了这两个文件(即已读取注释并找到了字符串),但是在运行该应用程序后,它们都没有设置照片或电话号码。

Here is what i do: 这是我的工作:

The following code should load all contacts and save their id and note. 以下代码应加载所有联系人并保存其ID和便笺。 Note that ContactInfo is just a simple class with variables to hold the contactId etc. (String contactId, String note, Byte[] Photo) and according get and set methods. 请注意,ContactInfo只是一个简单的类,具有用于保存contactId等的变量(字符串contactId,字符串注释,Byte []照片)以及相应的get和set方法。

public ArrayList<ContactInfo> loadAllContacts(ContentResolver cr) {
    ArrayList<ContactInfo> contactList = new ArrayList<ContactInfo>();

        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String contactId = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                ContactInfo contactInfo = new ContactInfo(contactId);

                // Get Note
                    String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                    String[] whereParams = new String[]{contactId,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
                            Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, where, whereParams, null); 
                    if (noteCur.moveToFirst()) { 
                        String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                        contactInfo.setNote(note);
                    } 
                    noteCur.close();                        

                contactList.add(contactInfo);                   
            }
        }

    return contactList;
}

The following code should update all contacts setting a photo (and for further testing, a phone number). 以下代码应更新所有设置照片的联系人(并进行进一步测试,包括电话号码)。 The setPhoto method I got from the following blog: Handling Contact Photos and because it worked perfectly in the testing AVD I thought that theres probably no error in it. 我从以下博客获得了setPhoto方法: 处理联系人照片,并且由于它在测试AVD中运行良好,所以我认为其中可能没有错误。

public void updateAllContacts(ContentResolver cr, ArrayList<ContactInfo> contactList) {
    while (!contactList.isEmpty()) {
        ContactInfo contact = contactList.remove(0);
        String contactId = contact.getContactId();

        setPhoto(cr,contact.getPhoto(),contactId);
        setPhoneNumber(cr,contact.getPhoneNumber(),contactId);
    }

}

public void setPhoneNumber(ContentResolver cr, String phoneNumber, String contactId) {
    ContentValues values = new ContentValues();

    values.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
    values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,phoneNumber);
    values.put(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_CUSTOM);

    cr.insert(ContactsContract.Data.CONTENT_URI, values);
}

public void setPhoto(ContentResolver cr, byte[] bytes, String contactId) {      
    ContentValues values = new ContentValues();
    int photoRow = -1;
    String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + contactId + " AND " + ContactsContract.Data.MIMETYPE + "=='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
    Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
    int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
    if (cursor.moveToFirst()) {
        photoRow = cursor.getInt(idIdx);
    }
    cursor.close();

    values.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
    values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
    values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
    values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);

    if (photoRow >= 0) {
        cr.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID + " = " + photoRow, null);
    } else {
        cr.insert(ContactsContract.Data.CONTENT_URI, values);
    }
}

The following routine I use to get the byte array from the *.png in the res folder of my app. 我使用以下例程从应用程序的res文件夹中的* .png获取字节数组。

public static byte[] getByteArrayFromResource(Resources rsrc,int id) {
    Bitmap bmp = BitmapFactory.decodeResource(rsrc,id);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bytes = stream.toByteArray();

    return bytes;
}

Finally, what I execute in my main routine, is: 最后,我在主例程中执行的是:

ArrayList<ContactInfo> contactList = new ArrayList<ContactInfo>();
ContactsAccessor contactsAccessor = new ContactsAccessor();
contactList = contactsAccessor.loadAllContacts(getContentResolver());

int test = 0;
for (int i=0; i<contactList.size(); i++) {
     ContactInfo contact = contactList.get(i);
     String note = contact.getNote();

     if (note.contains("TESTSHRAZAAM")) {                       
        contact.setPhoneNumber("12345");
        contact.setPhoto(ImageHandler.getByteArrayFromResource(getResources(),R.drawable.ic_eplus));
        test = test+1;
     }
 }

 contactsAccessor.updateAllContacts(getContentResolver(), contactList);

 if (test>0) Toast.makeText(WelchesNetzIcons.this,"Es wurden "+test+" Icons gesetzt.", Toast.LENGTH_SHORT).show();
 else Toast.makeText(WelchesNetzIcons.this, "Es wurden keine Icons gesetzt.", Toast.LENGTH_SHORT).show();

I geatly appreciate any suggestions on what I might be doing wrong here. 我非常感谢您对我在这里做错的任何建议。 Also, I tried to be as precise as I could, but if you are interested in or need any further information, please don't hesitate to ask. 另外,我尽力做到了精确,但如果您有兴趣或需要任何其他信息,请随时询问。

Thank you very much for your effort in helping me. 非常感谢您为我提供的帮助。

Best regards, Niklas 最好的问候,尼克拉斯

Try to use this code. 尝试使用此代码。 It works for me. 这个对我有用。

Your problem may be in wrong contact id or in wrong mimetype 您的问题可能出在错误的联系人ID或错误的模仿类型上

//looking for contact //寻找联络人

String select = String.format("%s=? AND %s='%s'", Phone.NUMBER, Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
String[] project = new String[] { Data.RAW_CONTACT_ID };
Cursor c = context.getContentResolver().query(Data.CONTENT_URI, project, select, new String[] { contact.getPhone() }, null);

if(c.moveToFirst()){
  rawContactId = c.getLong(c.getColumnIndex(Data.RAW_CONTACT_ID));
}

//set photo
Bitmap bit = //your photo
ByteArrayOutputStream streamy = new ByteArrayOutputStream(); 
bit.compress(CompressFormat.PNG, 0, streamy); 
byte[] photo = streamy.toByteArray();

ContentValues values = new ContentValues(); 

values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId); 
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1); 
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo); 
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE); 

ContactHelper.context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM