1. 程式人生 > >記錄一個bug permission denied for window type 2002

記錄一個bug permission denied for window type 2002

懸浮窗顯示的時候在8.0手機上總是提示需要開啟懸浮窗許可權

11-02 22:27:33.870 12386-12386/com.dahai.demo E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.dahai.demo, PID: 12386
                                                                      java.lang.RuntimeException: Unable to start service 
[email protected]
with Intent { act=com.dahai.demo.service.FloatService.ACTION_ADD_WINDOWS cmp=com.dahai.demo/.service.FloatService }: android.view.WindowManager$BadTokenException: Unable to add window [email protected] -- permission denied for window type 2002 at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3694) at android.app.ActivityThread.-wrap21(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1801) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6938) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) Caused by: android.view.WindowManager$BadTokenException: Unable to add window
[email protected]
-- permission denied for window type 2002 at android.view.ViewRootImpl.setView(ViewRootImpl.java:981) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:381) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:100) at com.dahai.demo.service.FloatService.createFloatView(FloatService.java:124) at com.dahai.demo.service.FloatService.onStartCommand(FloatService.java:219) at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3677) at android.app.ActivityThread.-wrap21(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1801) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6938) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

在網上找了很多解決方案都不行,最後研讀程式碼總算找到元凶了,這樣設定就ok啦

        // 設定窗體顯示型別
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }