一般我们都是在Activity中创建dialog的,无论是系统的AlertDialog还是我们自定义的Dialog。
我们只需设置title,message等信息,然后show出来即可。
可是在服务中呢,没有activity,dialog没有了依赖,那么怎么办呢? 这时,dialog就要以系统对话框的形式弹出了。在我们取得Dialog对象后,需给它设置类型,即:
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
1
看看这个TYPE的解释
/**
* Window type: system window, such as low power alert. These windows
* are always on top of application windows.
* In multiuser systems shows only on the owning user's window.
*/
public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;
在这里别忘了在Manifest中加上权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
1
最后来段示例代码
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Hello,My name is Message.");
builder.setNegativeButton("CANCEL", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 具体操作
}
});
final Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();