Skip to content

Instantly share code, notes, and snippets.

@GigigoGreenLabs
Last active November 10, 2015 08:53
Show Gist options
  • Save GigigoGreenLabs/08365f12028360832ba9 to your computer and use it in GitHub Desktop.
Save GigigoGreenLabs/08365f12028360832ba9 to your computer and use it in GitHub Desktop.
Check M Permissions class. This class has to grow
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
public class CheckPermissions {
public static final int REQUEST_CONTACTS = 1273;
private final Activity activity;
private final Dialog rationaleDialog;
private OnGrantedContactPermission onGrantedContactPermission;
public CheckPermissions(Activity activity, Dialog rationaleDialog) {
this.activity = activity;
this.rationaleDialog = rationaleDialog;
}
public void checkContactPermission() {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
if (onGrantedContactPermission != null) {
onGrantedContactPermission.onGratedContactPermission(true);
}
} else {
requestPhonePermission();
}
}
private void requestPhonePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.WRITE_CONTACTS)) {
if (rationaleDialog != null) {
rationaleDialog.show();
}
} else {
doRequestPhonePermissions();
}
}
private void doRequestPhonePermissions() {
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.WRITE_CONTACTS}, REQUEST_CONTACTS);
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == CheckPermissions.REQUEST_CONTACTS) {
if (verifyPermissions(grantResults)) {
if (onGrantedContactPermission != null) {
onGrantedContactPermission.onGratedContactPermission(true);
}
} else {
if (onGrantedContactPermission != null) {
onGrantedContactPermission.onGratedContactPermission(false);
}
}
}
}
private boolean verifyPermissions(int[] grantResults) {
if(grantResults.length < 1){
return false;
}
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
public interface OnGrantedContactPermission {
void onGratedContactPermission(boolean isGranted);
}
public void setOnGrantedContactPermissionListener(OnGrantedContactPermission onGrantedContactPermission) {
this.onGrantedContactPermission = onGrantedContactPermission;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment