Why does Settings.canDrawOverlays() method in Android 8 returns "false" when user grants permission to draw overlays and returns back to the app?

I'm developing the MDM app for parents to control children's devices and it uses permission SYSTEM_ALERT_WINDOW to display warnings on device if forbidden action has performed. On devices with SDK 23+ (Android 6.0) during installation the app checks the permission using this method:

Settings.canDrawOverlays(getApplicationContext()) 

and if this method returns false the app opens system dialog where user can grant the permission:

Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, REQUEST_CODE); 

But on device with SDK 26 (Android 8.0), when user has successfully granted permission and returned to the app by pressing back button, method canDrawOverlays() still returns false, until user doesn't close the app and starts it again or just chooses it in the recent apps dialog. I tested it on latest version of virtual device with Android 8 in Android Studio because I didn't have real device.

I've done a little research and additionally check the permission with AppOpsManager:

AppOpsManager appOpsMgr = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsMgr.checkOpNoThrow("android:system_alert_window", android.os.Process.myUid(), getPackageName()); Log.d(TAG, "android:system_alert_window: mode=" + mode); 

And so:

  • when the application does not have this permission, the mode is "2" (MODE_ERRORED) (canDrawOverlays() returns false) when the user
  • granted permission and returned to the application, the mode is "1" (MODE_IGNORED) (canDrawOverlays() returns false)
  • and if you now restart the app, the mode is "0" (MODE_ALLOWED) (canDrawOverlays() returns true)

Please, can anyone explain this behavior to me? Can I rely on mode == 1 of operation "android:system_alert_window" and assume that the user has granted permission?

9 Answers

I ran into the same problem. I use a workaround which tries to add an invisible overlay. If an exception is thrown the permission isn't granted. It might not be the best solution, but it works. I can't tell you anything about the AppOps solution, but it looks reliable.

Edit October 2020: As mentioned in the comments there might be a memory leak inside the WindowManager when the SecurityException is thrown, causing the workaround view not to be removed (even with explicit calls to removeView). For normal uses this should not be much of a problem, but avoid running too many checks in the same app session (Without testing it I'd assume anything below hundred should be alright).

/** * Workaround for Android O */ public static boolean canDrawOverlays(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true; else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { return Settings.canDrawOverlays(context); } else { if (Settings.canDrawOverlays(context)) return true; try { WindowManager mgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (mgr == null) return false; //getSystemService might return null View viewToAdd = new View(context); WindowManager.LayoutParams params = new WindowManager.LayoutParams(0, 0, android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT); viewToAdd.setLayoutParams(params); mgr.addView(viewToAdd, params); mgr.removeView(viewToAdd); return true; } catch (Exception e) { e.printStackTrace(); } return false; } } 
10

I've found this problems with checkOp too. In my case I have the flow which allows to redirect to settings only when the permission is not set. And the AppOps is set only when redirecting to settings.

Assuming that AppOps callback is called only when something is changed and there is only one switch, which can be changed. That means, if callback is called, user has to grant the permission.

if (VERSION.SDK_INT >= VERSION_CODES.O && (AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW.equals(op) && packageName.equals(mContext.getPackageName()))) { // proceed to back to your app } 

After the app is restored, checking with canDrawOverlays() starts worked for me. For sure I restart the app and check if permission is granted via standard way.

It's definitely not a perfect solution, but it should work, till we know more about this from Google.

EDIT: I asked google:

EDIT 2: Google fixes this. But it seem that the Android O version will be affected still.

4

Here is my all in one solution, this is a combination of others but serves well for most situations
First checks using the standard check according to Android Docs
Second Check is Using the AppOpsManager
Third and final check if all else fails is to try to display an overlay, if that fails it definitely aint gonna work ;)

static boolean canDrawOverlays(Context context) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && Settings.canDrawOverlays(context)) return true; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {//USING APP OPS MANAGER AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); if (manager != null) { try { int result = manager.checkOp(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, Binder.getCallingUid(), context.getPackageName()); return result == AppOpsManager.MODE_ALLOWED; } catch (Exception ignore) { } } } try {//IF This Fails, we definitely can't do it WindowManager mgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (mgr == null) return false; //getSystemService might return null View viewToAdd = new View(context); WindowManager.LayoutParams params = new WindowManager.LayoutParams(0, 0, android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT); viewToAdd.setLayoutParams(params); mgr.addView(viewToAdd, params); mgr.removeView(viewToAdd); return true; } catch (Exception ignore) { } return false; } 
3

Actually on Android 8.0 it returns true but only when you wait for 5 to 15 seconds and again query for the permission using Settings.canDrawOverlays(context) method.

So what you need to do is show a ProgressDialog to user with a message explaining about issue and run a CountDownTimer to check for overlay permission using Settings.canDrawOverlays(context) in onTick method.

Here is sample code:

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 100 && !Settings.canDrawOverlays(getApplicationContext())) { //TODO show non cancellable dialog new CountDownTimer(15000, 1000) { @Override public void onTick(long millisUntilFinished) { if (Settings.canDrawOverlays(getApplicationContext())) { this.cancel(); // cancel the timer // Overlay permission granted //TODO dismiss dialog and continue } } @Override public void onFinish() { //TODO dismiss dialog if (Settings.canDrawOverlays(getApplicationContext())) { //TODO Overlay permission granted } else { //TODO user may have denied it. } } }.start(); } } 
3

In my case I was targeting API level < Oreo and the invisible overlay method in Ch4t4's answer does not work as it does not throw an exception.

Elaborating on l0v3's answer above, and the need to guard against the user toggling the permission more than once, I used the below code (Android version checks omitted) :

In the activity / fragment :

Context context; /* get the context */ boolean canDraw; private AppOpsManager.OnOpChangedListener onOpChangedListener = null; 

To request the permission in the activity / fragment:

AppOpsManager opsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); canDraw = Settings.canDrawOverlays(context); onOpChangedListener = new AppOpsManager.OnOpChangedListener() { @Override public void onOpChanged(String op, String packageName) { PackageManager packageManager = context.getPackageManager(); String myPackageName = context.getPackageName(); if (myPackageName.equals(packageName) && AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW.equals(op)) { canDraw = !canDraw; } } }; opsManager.startWatchingMode(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, null, onOpChangedListener); startActivityForResult(intent, 1 /* REQUEST CODE */); 

And inside onActivityResult

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (onOpChangedListener != null) { AppOpsManager opsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE); opsManager.stopWatchingMode(onOpChangedListener); onOpChangedListener = null; } // The draw overlay permission status can be retrieved from canDraw log.info("canDrawOverlay = {}", canDraw); } } 

To guard against your activity being destroyed in the background, inside onCreate:

if (savedInstanceState != null) { canDraw = Settings.canDrawOverlays(context); } 

and inside onDestroy, stopWatchingMode should be invoked if onOpChangedListener is not null, similar to onActivityResult above.

It is important to note that, as of the current implementation (Android O), the system will not de-duplicate registered listeners before calling back. Registering startWatchingMode(ops, packageName, listener), will result in the listener being called for either matching operations OR matching package name, and in case both of them matches, will be called 2 times, so the package name is set to null above to avoid the duplicate call. Also registering the listener multiple times, without unregistering by stopWatchingMode, will result in the listener being called multiple times - this applies also across Activity destroy-create lifecycles.

An alternative to the above is to set a delay of around 1 second before calling Settings.canDrawOverlays(context), but the value of delay depends on device and may not be reliable. (Reference: )

3

If you check several times, it will work correctly ...

My Solution is :

 if (!Settings.canDrawOverlays(this)) { switchMaterialDraw.setChecked(false); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (Settings.canDrawOverlays(HomeActivity.this)){ switchMaterialDraw.setChecked(true); } } }, 500); switchMaterialDraw.setChecked(false); } else { switchMaterialDraw.setChecked(true); } 

As you know there is a known bug: Settings.canDrawOverlays(context) always returns false on some devices on Android 8 and 8.1. For now, the best answer is by @Ch4t4r with a quick test, but it still has flaws.

  1. It assumes that if the current Android version is 8.1+ we can rely on the method Settings.canDrawOverlays(context) but actually, we can't, as per multiple comments. On 8.1 on some devices, we still can get false even if the permission was just received.

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) return Settings.canDrawOverlays(context); //Wrong 
  2. It assumes that if we try to add a view to a window without the overlay permission the system will throw an exception, but on some devices it's not the case (a lot of Chinese manufacturers, for example Xiaomi), so we can't fully rely on try-catch

  3. And the last thing, when we add a view to a window and on the next line of code we remove it - the view won't be added. It takes some time to actually add it, so these lines won't help much:

    mgr.addView(viewToAdd, params); mgr.removeView(viewToAdd); // the view is removed even before it was added 

this results to a problem that if we try to check if the view is actually attached to a window we will get false instantly.


Ok, how we gonna fix this?

So I updated this workaround with the overlay permission quick-test approach and added a little delay to give some time to a view to attach to a window. Because of this we will use a listener with a callback method which will notify us when the test is completed:

  1. Create a simple callback interface:

    interface OverlayCheckedListener { void onOverlayPermissionChecked(boolean isOverlayPermissionOK); } 
  2. Call it when the user supposed to enable the permission and we need to check whether he acutally enabled it or not (for exmaple in onActivityResult()):

    private void checkOverlayAndInitUi() { showProgressBar(); canDrawOverlaysAfterUserWasAskedToEnableIt(this, new OverlayCheckedListener() { @Override public void onOverlayPermissionChecked(boolean isOverlayPermissionOK) { hideProgressBar(); initUi(isOverlayPermissionOK); } }); } 
  3. The method itself. The magic number 500 - how many milliseconds we delay before asking a view if it is attached to a window.

    public static void canDrawOverlaysAfterUserWasAskedToEnableIt(Context context, final OverlayCheckedListener listener) { if(context == null || listener == null) return; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { listener.onOverlayPermissionChecked(true); return; } else { if (Settings.canDrawOverlays(context)) { listener.onOverlayPermissionChecked(true); return; } try { final WindowManager mgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (mgr == null) { listener.onOverlayPermissionChecked(false); return; //getSystemService might return null } final View viewToAdd = new View(context); WindowManager.LayoutParams params = new WindowManager.LayoutParams(0, 0, android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSPARENT); viewToAdd.setLayoutParams(params); mgr.addView(viewToAdd, params); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (listener != null && viewToAdd != null && mgr != null) { listener.onOverlayPermissionChecked(viewToAdd.isAttachedToWindow()); mgr.removeView(viewToAdd); } } }, 500); } catch (Exception e) { listener.onOverlayPermissionChecked(false); } } } 

NOTE: This is not a perfect solution, if you come up with a better solution please let me know. Also, I faced some strange behavior due to postDelayed actions but seems that the reason is in my code rather than in the approach.

Hope this helped someone!

Kotlin coroutines version based on answer of @Vikas Patidar

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // see if (requestCode == <your_code> && !PermsChecker.hasOverlay(applicationContext)) { lifecycleScope.launch { for (i in 1..150) { delay(100) if (PermsChecker.hasOverlay(applicationContext)) { // todo update smth break } } } } } 
  1. If we cannot trust the system API return value, we can try to detect whether we have the draw_overlay permission.
  2. Regardless of whether the user grants it or not, we can try to add a floating window. According to our experience, not all phone models will throw exceptions without draw_overlay permission.
  3. When adding a view, you can add an attribute, FLAG_WATCH_OUTSIDE_TOUCH, and add click event listening outside the layout.
  4. If the floating window is added successfully, you will be able to obtain click events within or outside the view, thereby confirming that the draw_overlay permission have been granted.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like