如何让 AlertDialog 框出现在应用程序之外?

How do I make the AlertDialog box appear outside the app?

@Override
public void run() {
    //Create thread that can alter the UI
    AlarmPage.this.runOnUiThread(new Runnable() {
        public void run() {
            cal = Calendar.getInstance();
            //See if current time matches set alarm time
            if((cal.get(Calendar.HOUR_OF_DAY) == alarmTime.getCurrentHour()) 
                    && (cal.get(Calendar.MINUTE) == alarmTime.getCurrentMinute())){
                //If the sound is playing, stop it and rewind
                if(sound.isPlaying()){
                    ShowDialog();
                    alarmTimer.cancel();
                    alarmTask.cancel();
                    alarmTask = new PlaySoundTask();
                    alarmTimer = new Timer();
                    alarmTimer.schedule(alarmTask, sound.getDuration(), sound.getDuration());
                }
                sound.start();
            }       
        }
    });
}

public void ShowDialog() {
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    alertDialog.setTitle("REMINDER!");
    alertDialog.setMessage("Turn off alarm by pressing off");

    alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT);
        }
    });

    alertDialog.show();
}

我正在制作一个通知用户的简单闹钟应用程序。我想制作一个警报框,让用户可以选择在警报关闭时关闭警报。我能够制作警告框,但它只出现在应用程序中而不是应用程序之外。我知道该应用程序必须在后台运行 运行。如果我需要显示更多代码或更具体,请询问。

这样做会创建一个没有 ContentViewActivity 或与之关联的 View 并在您的 onCreate 中调用您的 alertDialog 方法还记得设置使用 ColourDrawable

ActivityTransparent 的背景

而且 activity 看起来像一个对话框或符合您的喜好,您也可以回退到 Themes,这样您就可以将 Activity 设置为 Dialog 并像对待 Dialog 一样使用 DialogFragment

添加一行为:

public void ShowDialog() {
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

    alertDialog.setTitle("REMINDER!");
    alertDialog.setMessage("Turn off alarm by pressing off");

    alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
        }
    });

    alertDialog.show();
    // line you have to add
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}

现在检查。

如果答案没有解决您的问题,请不要接受,这是误导。

接受的答案不正确,因为它永远不会在您的应用程序之外工作。

原因:

  1. 它需要一个 activity 上下文而不是应用程序上下文。

  2. 如果您提供应用程序上下文,您的应用程序将因 IllegalArgumentException 而崩溃 - 您需要使用 Theme.AppCompat 或其后代...

如果您需要问题中实际陈述的功能,您必须有一个单独的 activity 主题作为对话框,例如 here

或者您可以使用 window 管理器向 window 添加自定义视图,并使其成为系统级警报,例如 here