user6791239 user6791239 - 3 months ago 12
Android Question

Android Marshmallow security exception when getting contacts

Can anyone please suggest me what changes should I make in my code for retrieving contacts from contact list in Android. The logic which I have written is working perfect for lollipop and below but for above lollipop it's crashing saying security exception..

Answer

Please refer to https://developer.android.com/training/permissions/requesting.html

"Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app."

Permissions are classified as normal and dangerous.

The following code checks if the app has permission to read the user's contacts, and requests the permission if necessary:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

    // Show an expanation to the user *asynchronously* -- don't block
    // this thread waiting for the user's response! After the user
    // sees the explanation, try again to request the permission.

} else {

    // No explanation needed, we can request the permission.

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant. The callback method gets the
    // result of the request.
}
}
Comments