写好Alter功能块后,在alter.show()语句前加入:
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
注:alter为AlertDialog类型对象
然后在AndroidManifest.xml中加入权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission>
下面进行简单的解释:
如果只在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(); 
Android UI学习 - 对话框 (AlertDialog & ProgressDialog)
http://android.blog.51cto.com/268543/333769
android在Service,BroadCast onReceiver()中弹出Dialog对话框
原文:http://my.oschina.net/thc/blog/493325