Reference:
http://stackoverflow.com/questions/32652533/android-system-overlay-windowhttp://caiyao.name/2016/03/02/Android-6-0%E8%BF%90%E8%A1%8C%E6%97%B6%E6%9D%83%E9%99%90%E5%B0%8F%E7%BB%93/
Error message:
Unable to add window android.view.ViewRoot$W@XXXXXXXX — permission denied for this window typeCode snippet:
在 Android 6.0+ (SDK 23+) 用 TYPE_SYSTEM_ALERT,即使在 Manifest裡有宣告 permission<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />依舊會出現上面的 Error message.
這時候要先透過 Settings.canDrawOverlays檢查 app是否有權限,如果沒有的話,發出 Settings.ACTION_MANAGE_OVERLAY_PERMISSION 的 Intent,讓使用者打開權限
@Overrideprotected void onResume() { super.onResume(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(!Settings.canDrawOverlays(this)){ requestAlertWindowPermission(); } else{ // do something } } else{ // do something } }
private static final int REQUEST_CODE = 1; private void requestAlertWindowPermission() { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); intent.setData(Uri.parse("package:" + getPackageName())); startActivityForResult(intent, REQUEST_CODE); } @Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Settings.canDrawOverlays(this)) { Log.i(TAG, "onActivityResult granted");// do something } else{ Log.i(TAG, "onActivityResult not granted"); } } } }
沒有留言:
張貼留言