问题
I am currently working on a project in which I want to access the mobile contacts, So I have managed to create account with accountmanager
and also able to perform Syncadapter
operation. I could see my account got created in the mobile settings->Accounts
. However, when I try to get all the contacts with my account with below code ,it does not work. Its showing all apps(google.com and WhatsApp.com) contacts except my app account contacts.
Cursor cursor = getContext().getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.DIRTY, ContactsContract.RawContacts.ACCOUNT_TYPE},
null,
null,
null);
if (cursor != null && cursor.getCount() >0) {
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d("Dirty",cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.DIRTY)));
Log.d("ACCountType",cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
cursor.moveToNext();
}
cursor.close();
}
What I dont understand is do I need to create ContentProvider
and insert all contacts back to Contactsprovider
on behalf of my account?
回答1:
Not sure if you've fully understood how the ContactsProvider works.
There are a few things that you should know:
- Every RawContact is uniquely assigned to one specific account, it can not belong to more than one account (hence your app usually can't sync existing contacts, because they already have an account).
- All apps have the same view on all the contacts, in particular all apps can see and modify all contacts (given they have the permissions), though there are a few exceptions to that rule.
When you sync a contact to your account you must specify your account as shown on ContactsContract.RawContacts
ContentValues values = new ContentValues(); values.put(RawContacts.ACCOUNT_TYPE, accountType); values.put(RawContacts.ACCOUNT_NAME, accountName); Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values); long rawContactId = ContentUris.parseId(rawContactUri);
When you read contacts you get contacts of all accounts, unless you specify Uri query parameters or a selection:
Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName) .appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType) .build(); Cursor c1 = getContentResolver().query(rawContactUri, RawContacts.STARRED + "<>0", null, null, null)
This query returns all starred contacts of the specified account.
If your code operates as a sync adapter you also have to add the Uri query parameter CALLER_IS_SYNC_ADAPTER, otherwise you may get different results for many operations.
来源:https://stackoverflow.com/questions/37945724/no-contacts-for-my-accountmanager-account