I am creating a method that gets all names and numbers from an Android phone.
private void getContactList() {
Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String aNameFromContacts[] = new String[contacts.getCount()];
String aNumberFromContacts[] = new String[contacts.getCount()];
int i = 0;
int nameFieldColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int numberFieldColumnIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while(contacts.moveToNext()) {
String contactName = contacts.getString(nameFieldColumnIndex);
aNameFromContacts[i] = contactName ;
String number = contacts.getString(numberFieldColumnIndex);
aNumberFromContacts[i] = number ;
i++;
}
contacts.close();
}
In the Manifest, I have added:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
Unfortunately, I still get an exception:
java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{cb99505 8760:net.zedge.vibtest/u0a80} (pid=8760, uid=10080) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS
Why might this be?
Prior to Android Marshmallow, declaring the permissions in manifest was enough and system used to grant those permissions during installation. But starting from Android M declaring the permissions is not enough. The authority to grant the permission has been transferred to user. You need to request those permissions at runtime in order to allow users to grant the permissions.
Follow this official documentation for implementation details.