悬浮窗+Dialog中的坑

功能需求:

点击悬浮窗中的按钮显示一个Dialog

踩坑之路:

先是Context

Dialog adDialog = new Dialog(context, R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();

崩溃,log:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

换成ApplicationContext

Dialog adDialog = new Dialog(context.getApplicationContext(), R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();

崩溃,log:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

换成Activity

Dialog adDialog = new Dialog(activity, R.style.DialogStyle);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();

第一次启动APP,点击显示悬浮窗,成功!退出APP再次进入,点击悬浮窗,崩溃!log:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@41e48918 is not valid; is your activity running?

添加 TYPE_SYSTEM_ALERT

在代码中添加:adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

Dialog adDialog = new Dialog(context.getApplicationContext(), R.style.DialogStyle);
adDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
adDialogView = LayoutInflater.from(context).inflate(R.layout.dialog,null);
adDialog.setContentView(adDialogView);
adDialog.show();

并且在manifest中增加权限:

 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

此时,无论是使用context或者activity还是context.getApplicationContext()都可以正常显示Dialog

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容