错误全log信息如下:
08-14 12:54:17.073 6411-6411/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.administrator.myapplication, PID: 6411
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@d4521e8 -- permission denied for this window type
at android.view.ViewRootImpl.setView(ViewRootImpl.java:591)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at com.example.administrator.myapplication.FloatView.show(FloatView.java:78)
at com.example.administrator.myapplication.MainActivity.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
回看AndroidMainifest.xml时添加了如下权限了额:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
其实android6.0添加了运行时权限,因此我们在使用弹出框的地方加入如下代码:
public void permission(){
if (Build.VERSION.SDK_INT >= 23) {
if(!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(intent);
return;
} else {
//Android6.0以上
if (mFloatView!=null && mFloatView.isShow()==false) {
mFloatView.show();
}
}
} else {
//Android6.0以下,不用动态声明权限
if (mFloatView!=null && mFloatView.isShow()==false) {
mFloatView.show();
}
}
}
}
这时需要权限时会先弹到权限申请页面。