Skip to content

Instantly share code, notes, and snippets.

@truongngoclinh
Last active November 7, 2022 06:53
Show Gist options
  • Save truongngoclinh/1e2403d4eec36e728cb69ab5ac4eea59 to your computer and use it in GitHub Desktop.
Save truongngoclinh/1e2403d4eec36e728cb69ab5ac4eea59 to your computer and use it in GitHub Desktop.
Handle permission on Android 6.0 and above versions.
public class Activity extends AppCompatActivity {
private static final String TAG = "FVPermissionsActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FVPermissionUtils.isPermissionGranted(this, FVPermissionUtils.Permissions.OVERLAY)) {
startFloatingService();
} else {
FVPermissionUtils.requestPermission(this, FVPermissionUtils.Permissions.OVERLAY);
}
}
private void startFloatingService() {
Log.d(TAG, "startFloatingService: ");
startService(new Intent(this, FVService.class));
finish();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: ");
if (FVPermissionUtils.verifyPermissions(this, permissions, grantResults)) {
onPermissionGranted(requestCode);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult: ");
if (requestCode == FVPermissionUtils.REQUEST_PERMISSION_SETTING) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(this)) {
startFloatingService();
} else {
Snackbar.make(this.findViewById(android.R.id.content), getResources().getString(R.string.dialog_permission_message), Snackbar.LENGTH_LONG);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
protected void onPermissionGranted(int requestCode) {
Log.d(TAG, "onPermissionGranted: ");
if (requestCode == FVPermissionUtils.Permissions.OVERLAY.getRequestCode()) {
startFloatingService();
}
}
}
public class PermissionUtils {
private static final String TAG = "FVPermissionUtils";
public static final int REQUEST_PERMISSION_SETTING = 0x1739;
public static boolean sShownRationalDialogOnRequest = false;
public static boolean isPermissionGranted(Context context, Permissions permission) {
return ContextCompat.checkSelfPermission(context, permission.getPermission())
== PackageManager.PERMISSION_GRANTED;
}
/**
* Requests the permission.
* If the permission has been denied previously, a dialog will prompt the user to grant the
* permission, otherwise it is requested directly.
*
* @param activity
*/
public static void requestPermission(final Activity activity, final Permissions permission) {
Log.d(TAG, "requestPermission: ");
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission.getPermission())) {
Log.d(TAG, "requestPermission: ");
sShownRationalDialogOnRequest = true;
showRationaleDialog(activity, R.string.dialog_permission_positive_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, new String[]{permission.getPermission()},
permission.getRequestCode());
}
});
} else {
Log.d(TAG, "requestPermission: request directly");
// Permission has not been granted yet. Request it directly.
sShownRationalDialogOnRequest = false;
ActivityCompat.requestPermissions(activity, new String[]{permission.getPermission()},
permission.getRequestCode());
}
}
/**
* Requests the permission.
* If the permission has been denied previously, a dialog will prompt the user to grant the
* permission, otherwise it is requested directly.
*
* @param fragment
*/
public static void requestPermission(final Fragment fragment, final Permissions permission) {
if (fragment.shouldShowRequestPermissionRationale(permission.getPermission())) {
sShownRationalDialogOnRequest = true;
showRationaleDialog(fragment.getContext(), R.string.dialog_permission_positive_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fragment.requestPermissions(new String[]{permission.getPermission()},
permission.getRequestCode());
}
});
} else {
// Permission has not been granted yet. Request it directly.
sShownRationalDialogOnRequest = false;
fragment.requestPermissions(new String[]{permission.getPermission()},
permission.getRequestCode());
}
}
private static void showRationaleDialog(Context context, @StringRes int posTextRes,
DialogInterface.OnClickListener callback) {
Log.d(TAG, "showRationaleDialog: ");
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.dialog_permission_message);
builder.setPositiveButton(posTextRes, callback);
builder.setNegativeButton(R.string.dialog_permission_negative_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
/**
* Check that all given permissions have been granted by verifying that each entry in the
* given array is of the value {@link PackageManager#PERMISSION_GRANTED}.
*/
public static boolean verifyPermissions(final Activity activity, final String[] permissions, int[] grantResults) {
// At least one result must be checked.
if (grantResults.length < 1) {
return false;
}
// Verify that each required permission has been granted, otherwise return false.
for (int i = 0; i < permissions.length; i++) {
int result = grantResults[i];
final String permission = permissions[i];
if (result != PackageManager.PERMISSION_GRANTED) {
boolean shouldShowRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
permission);
if (!shouldShowRationale) {
// it means user has selected "never ask again"
if (sShownRationalDialogOnRequest) {
return false;
}
sShownRationalDialogOnRequest = false;
showRationaleDialog(activity, R.string.dialog_permission_positive_button, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (permission.equals(Permissions.OVERLAY.getPermission())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
activity.startActivityForResult(myIntent, REQUEST_PERMISSION_SETTING);
}
} else {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
}
}
});
}
return false;
}
}
return true;
}
// Dangerous permission enum
public enum Permissions {
// CAMERA
CAMERA(Manifest.permission.CAMERA, 1),
// STORAGE
READ_STORAGE(Manifest.permission.READ_EXTERNAL_STORAGE, 2),
WRITE_STORAGE(Manifest.permission.WRITE_EXTERNAL_STORAGE, 3),
// OVERLAY
OVERLAY(Manifest.permission.SYSTEM_ALERT_WINDOW, 2),;
private final String permission;
private final int requestCode;
Permissions(String value, int requestCode) {
this.permission = value;
this.requestCode = requestCode;
}
public String getPermission() {
return permission.toString();
}
public int getRequestCode() {
return requestCode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment