Android service中弹出dialog 权限变动与用法

Android service中弹出dialog 权限变动与用法

专注于Android开发,分享经验总结,欢迎加入

QQ群

最近在做音视频聊天需要在service中弹出聊天界面,开发期间遇到的坑特此记录(Android9系统)
报错信息有如下:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?	

android.view.WindowManager$BadTokenException Unable to add window android.view.ViewRootImpl$W@fa525bc -- permission denied for window type 2002	
permission denied for window type 2003		
permission denied for window type 2007

遇到此类信息都是WindowManager.LayoutParams 设置的type不对

这是因为android O(Android8系统)对悬浮窗的设计做了一些修改,在使用android.permission.SYSTEM_ALERT_WINDOW 权限的应用无法再使用以下窗口类型来在其他应用和系统窗口上显示悬浮窗:

WindowManager.LayoutParams.TYPE_PRIORITY_PHONE

WindowManager.LayoutParams.TYPE_PHONE

WindowManager.LayoutParams.TYPE_SYSTEM_ERROR

WindowManager.LayoutParams.TYPE_SYSTEM_ALERT

WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY

正确使用如下:在dialog调用show()方法之前设置type

Window window = mAlertDialog.getWindow();
if (window != null) {
    WindowManager.LayoutParams attributes = window.getAttributes();
    if (attributes != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            attributes.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            attributes.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
    }
    window.setAttributes(attributes);
}
mAlertDialog.show();

记得在AndroidManifest.xml 写加入权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
在Android6.0之后还需动态申请权限

微信公众号 -->> 他晓 (欢迎加入)

公众号

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值