悬浮窗+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中增加权限:

 

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

你可能感兴趣的:(悬浮窗+Dialog中的坑)