anroid中常有逻辑需要弹出AlertDialog,用于提醒、引导用户。
一.常见的AlertDialog都是在Activity中使用,但在service、广播等非Activity组件中使用AlertDialog时需要加入
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
同时在Manifest.xml中加入如下权限声明。
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
具体使用AlertDialog的代码如下:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("是否接受文件?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("否", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog ad = builder.create();
// ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG); //系统中关机对话框就是这个属性
ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
ad.setCanceledOnTouchOutside(false); //点击外面区域不会让dialog消失
ad.show();
二.使用单选按钮对话框
final CharSequence[] items = getResources().getStringArray(R.array.mode_select_setting_entries);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.mode_select_tips);
builder.setSingleChoiceItems(items, mCurrentMode, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
….
}
});
AlertDialog alert = builder.create();
alert.show();
三。遇到的问题处理
使用AlertDialog时会遇到这个异常:Unable to add window -- token null is not for an application。
该异常的原因是传入的Context不是Activity,其对应的WindowManager.LayoutParams.token字段为空。
解决方法:1.传入Acitivity--Context,适用于页面弹出对话框;
2.传入非Activity--Context,但需要按照如下设置Dialog对应的window类型;
<pre code_snippet_id="151629" snippet_file_name="blog_20140110_3_3734477" name="code" class="java">dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
并在Apk--manifest中加入对应的权限,
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />