Permission denied for window type 2002 in Android Studio

孤街浪徒 提交于 2019-11-28 11:22:37

This is occurring because the targetSdkVersion in the example and your targetSdkVersion are different. Try reducing it to 22 or use the flag TYPE_APPLICATION_OVERLAY instead of TYPE_PHONE in WindowManager.LayoutParams:

WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 

This worked for me.. I'm sure it can be simplified, but it works perfectly otherwise.
Simply replace TYPE_PHONE with TYPE_APPLICATION_OVERLAY if (and only if) user is equal or above Oreo:

final WindowManager.LayoutParams params;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
    } else {
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
    }

By changing targetSdkVersion to 22, the issue will be solved partially. For devices above 22 you will get the same error. I found the following answer in stack overflow but didn't remember the link. You can try the following code:

private void createFloatView() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkDrawOverlayPermission();
    } else {
        createView();
    }
}

public void checkDrawOverlayPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!Settings.canDrawOverlays(getContext())) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getActivity().getPackageName()));
            startActivityForResult(intent, CommonVariables.REQUEST_CODE);
        } else {
            createView();
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CommonVariables.REQUEST_CODE) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(getContext())) {
                createView();
            }
        }
    }
}

 private int CommonVariables.REQUEST_CODE = 5463 & 0xffffff00
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!