简体   繁体   中英

Android programmatically inserted contact isn't linked to my app

I have created a custom Account for my app using the following code:

    Account account = new Account(username, accountType);
    ContentResolver.setIsSyncable(account, context.getString(R.string.CONTACT_AUTHORITY), 1);
    ContentResolver.setSyncAutomatically(account, context.getString(R.string.CONTACT_AUTHORITY), true);
    if(accManager.addAccountExplicitly(account, password, userData)) {
        Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, account.type);
        context.setAccountAuthenticatorResult(intent.getExtras());
        context.setResult(Activity.RESULT_OK);
        return account;
    } else {
        // display error
    }

And then I tried to insert a new contact using the following:

// insert new contact
ContentValues values = new ContentValues();
values.put(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType);
values.put(ContactsContract.RawContacts.ACCOUNT_NAME, accountName);
Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
Log.d("ABC", "New raw contact id = " + rawContactId);

// insert new rawContact id
values.clear();
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "zzzzzawesome");
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

I was able to insert the new contact, but the problem is when i look at that contact in my contact list, it doesn't have my app's icon in the 'Connected Via' section, instead it shows a phone icon, any idea why?

I'm using samsung S5 for testing btw.

在此处输入图片说明

I finally solved it, the problem lies with the absence of a SyncAdapter service implementation. After adding the following in AndroidManifest.xml the problem solved.

    <service
        android:name=".authenticator.ContactsSyncAdapterService"
        android:exported="true">
        <intent-filter>
            <action android:name="android.content.SyncAdapter" />
        </intent-filter>
        <meta-data
            android:name="android.content.SyncAdapter"
            android:resource="@xml/sync_contacts" />
    </service>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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