在日常的开发过程中,经常需要在全局范围内,控制一些信息。比如说,网络状况。我们首先想到的当然是在Application中,进行广播的监听,但是由于Dialog中Context需要的是个Activity,让我们总也不能够得逞。
最近发现了在Applcation中,可以实现弹出Dialog。
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("你想恢复下载 ?").setCancelable(false).setPositiveButton("删除", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).setNeutralButton("恢复", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
***alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);***
alert.show();
注意看清楚倒数第二行代码,然后在Manifest中添加一个,
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
即可。