How to handle SYSTEM_ALERT_WINDOW permission not being auto-granted on some pre-Marshmallow devices

1) on pre-API 23, the permission is already given, because the user granted it upon install.

EDIT: it seems there is a bug on Android 6 (that will get fixed on 6.0.1), that if the user has denied this permission , the app will crash with SecurityException. No idea how Google fixed it though.

2) This way:

public static void requestSystemAlertPermission(Activity context, Fragment fragment, int requestCode) {
    if (VERSION.SDK_INT < VERSION_CODES.M)
        return;
    final String packageName = context == null ? fragment.getActivity().getPackageName() : context.getPackageName();
    final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName));
    if (fragment != null)
        fragment.startActivityForResult(intent, requestCode);
    else
        context.startActivityForResult(intent, requestCode);
}

Then, in the onActivityResult, you can check if the permission is given or not, as such:

@TargetApi(VERSION_CODES.M)
public static boolean isSystemAlertPermissionGranted(Context context) {
    final boolean result = VERSION.SDK_INT < VERSION_CODES.M || Settings.canDrawOverlays(context);
    return result;
}

EDIT: for the time being, if you publish an app to the Play Store, your app will be auto-granted with this permission. You can read about it here. When I asked about it, I thought it was a part of Android itself, as I thought all we need is to target a high enough value for targetSdkVersion. What Google wrote to me (here) is that they wanted to avoid issues on popular apps.

I suggest handling this permission correctly even if you will get it auto-granted.

Leave a Comment