Android Creating Overlay (always-on-top) Windows Granting SYSTEM_ALERT_WINDOW Permission on android 6.0 and above

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

From android 6.0 this permission needs to grant dynamically,

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Throwing below permission denied error on 6.0,

Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@86fb55b -- permission denied for this window type

Solution :-

Requesting Overlay permission as below,

if(!Settings.canDrawOverlays(this)){
    // ask for setting 
     Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
     Uri.parse("package:" + getPackageName()));
     startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION);
}

Check for the result,

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_OVERLAY_PERMISSION) {
        if (Settings.canDrawOverlays(this)) {
            // permission granted...
        }else{
            // permission not granted...
        }
    }
}


Got any Android Question?