我需要在后台服务中提示alertDialog,但是由于错误的上下文而崩溃,我该如何处理它,哪里可以获得正确的上下文?
答案 0 :(得分:3)
服务类内的代码打开AlertDialog
private void showAlertDialog() {
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
final CharSequence[] items = { getString(R.string.test1), getString(R.string.tes2), getString(R.string.test3), getString(R.string.cancel) };
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("Title");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(getString(R.string.test1))) {
dialog.dismiss();
} else if (items[item].equals(getString(R.string.test2))) {
dialog.dismiss();
} else if (items[item].equals(getString(R.string.test3))) {
}else if (items[item].equals(getString(R.string.cancel))) {
dialog.dismiss();
}
}
});
alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
alert.show();
alert.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface arg0) {
}
});
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
}
您必须在清单文件中添加权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
您可以根据需要在警告对话框中执行自定义。
完成强>
答案 1 :(得分:1)
接受的答案在Oreo +中不起作用 请在WindowManager.LayoutParams中使用标志TYPE_APPLICATION_OVERLAY而不是TYPE_PHONE或SYSTEM_ALERT: 使用
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
代替
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
答案 2 :(得分:0)
1,您必须设置:mDialog.getWindow().setType(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
2,设置权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />