android service Dialog 弹出框

android service Dialog 弹出框

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

Caused by: android.view.WindowManager$BadTokenException:ide

  下面说下为何出现这个异常,缘由很简单,是因为 AlertDialog 的显示是依赖于一个肯定的Activity,因此要想在 Service 中实现弹出来,须要作以下配置:ui

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

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

  例如:code

  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();
    }

 

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

 

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

 

总结:以上作法就是声明咱们要弹出的这个提示框是一个系统的提示框,即全局性质的提示框,因此只要手机处于开机状态,不管它如今处于何种界面之下,只要调用alterObj.show(),就会弹出提示框来。blog

相关文章
相关标签/搜索