在 Android 6.0 及更高版本上授予 SYSTEM ALERT WINDOW 許可權

從 android 6.0 開始,此許可權需要動態授予,

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

在 6.0 以下投擲許可權被拒絕錯誤,

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

解決方案: -

請求覆蓋許可權如下,

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);
}

檢查結果,

@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...
        }
    }
}