android service Dialog 弹出框

  相信大家第一次在Service中实现 AlertDialog 弹出框时,都会遇到应用闪退然后报出这个异常:

Caused by: android.view.WindowManager$BadTokenException:

  下面说下为什么出现这个异常,原因很简单,是由于 AlertDialog 的显示是依赖于一个确定的Activity,所以要想在 Service 中实现弹出来,需要做如下配置:

1、安装常规写好 AlertDialog 功能块后,在alertObj .show()语句前加入:

  alertObj.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

  例如:

  private void showHostOnlineAlert(){
        final AlertDialog dialog =new AlertDialog.Builder(BackgroudService.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//set background was transparent
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//需要添加的语句
        dialog.show();
    }

 

2、在AndroidManifest.xml中加入权限:

 

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

 

总结:以上做法就是声明我们要弹出的这个提示框是一个系统的提示框,即全局性质的提示框,所以只要手机处于开机状态,无论它现在处于何种界面之下,只要调用alterObj.show(),就会弹出提示框来。

相关文章:

  • 2022-12-23
  • 2022-02-01
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2022-02-09
  • 2021-08-18
猜你喜欢
  • 2022-12-23
  • 2022-02-06
  • 2021-04-14
  • 2021-10-10
  • 2022-12-23
  • 2022-12-23
  • 2021-04-08
相关资源
相似解决方案