android在Service,BroadCast onReceiver()中弹出Dialog对话框,即全局性对话框

时间:2022-11-01 15:51:23

转自:http://jy0329.blog.163.com/blog/static/147466002201351931737303/

写好Alter功能块后,在alter.show()语句前加入:

<span style="color:#ff0000;">alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);</span>

注:alter为AlertDialog类型对象

然后在AndroidManifest.xml中加入权限:

<span style="color:#ff0000;"><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission></span>


下面进行简单的解释:

如果只在Service中写入常在Activity中使用的创建Alter的代码,运行时是会发生错误的,因为Alter的显示需要依附于一个确定的Activity类。而以上做法就是声明我们要弹出的这个提示框是一个系统的提示框,即全局性质的提示框,所以只要手机处于开机状态,无论它现在处于何种界面之下,只要调用alter.show(),就会弹出提示框来。

demo如下:

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setMessage("Are you sure you want to exit?") 
       .setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
                MyActivity.this.finish(); 
           } 
       }) 
       .setNegativeButton("No", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int id) { 
                dialog.cancel(); 
           } 
       }); 
AlertDialog alert = builder.create(); 
  alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
  alert.show();