I am working on an application where I need a user contact picture to be shown if available.
Below is the code for asking read_contacts permission:
public void requestPermissionOrShowRationale(Permission permission) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission.permission)) {
PermissionRationaleDialogFragment dialogFragment =
PermissionRationaleDialogFragment.newInstance(permission);
dialogFragment.show(getSupportFragmentManager(), FRAGMENT_TAG_RATIONALE);
} else {
requestPermission(permission);
}
}
public void requestPermission(Permission permission) {
Timber.i("Requesting permission: " + permission.permission);
ActivityCompat.requestPermissions(this, new String[] { permission.permission }, permission.requestCode);
}
public enum Permission {
READ_CONTACTS(
Manifest.permission.READ_CONTACTS,
PERMISSIONS_REQUEST_READ_CONTACTS,
R.string.permission_contacts_rationale_title,
R.string.permission_contacts_rationale_message
),
WRITE_CONTACTS(
Manifest.permission.WRITE_CONTACTS,
PERMISSIONS_REQUEST_WRITE_CONTACTS,
R.string.permission_contacts_rationale_title,
R.string.permission_contacts_rationale_message
);
& permission call from the activity as below:
private void checkAndRequestPermissions() {
if (!hasPermission(Permission.READ_CONTACTS)) {
requestPermissionOrShowRationale(Permission.READ_CONTACTS);
}
}
Everything is working fine when I am using targetsdk 23. after changing targetsdk to 26 or up the permission doesn't work. unless I manually turn it off & on from the app permission settings to get the contacts.
Super easy and best solution i have found for my question is TedPermission https://github.com/ParkSangGwon/TedPermission
I have removed all the existing codes for the permission and used the below magic code :)
setLayout(R.layout.welcome);
TedPermission.with(this)
.setPermissionListener(permissionlistener)
.setPermissions(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS)
.setDeniedMessage("This permission is required to show Contact Pictures and Email Address Suggestions.\n\nPlease turn on this permissions at [Setting] > [Permission]")
.check();
PermissionListener permissionlistener = new PermissionListener() {
@Override
public void onPermissionGranted() {
}
}
@Override
public void onPermissionDenied(ArrayList<String> deniedPermissions) {
Toast.makeText(WelcomeMessage.this, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};