美文网首页
悬浮窗+Dialog中的坑

悬浮窗+Dialog中的坑

作者: BlackNeko | 来源:发表于2016-07-26 11:38 被阅读699次

    功能需求:

    点击悬浮窗中的按钮显示一个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

    相关文章

      网友评论

          本文标题:悬浮窗+Dialog中的坑

          本文链接:https://www.haomeiwen.com/subject/ywynjttx.html