簡體   English   中英

如何使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();
}

我正在制作一個簡單的鬧鍾應用程序,通知用戶。 我想制作一個警報框,使用戶可以選擇在警報關閉時將其關閉。 我能夠制作警報框,但它僅出現在應用程序中,而不出現在應用程序外部。 我了解該應用必須在后台運行。 如果我需要顯示更多代碼或更具體,請問一下。

將行添加為:

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. 它需要活動上下文而不是應用程序上下文。

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

如果你需要的功能的問題卻規定你必須有主題的對話就像一個獨立的活動在這里

或者,您可以使用窗口管理器向窗口中添加自定義視圖,並使其像此處一樣成為系統級警報。

這樣做會創建一個沒有ContentView或與之關聯的ViewActivity ,並在onCreate調用您的alertDialog方法時還記得使用ColourDrawableActivity的背景設置為Transparent

而且該活動看起來像一個對話框或適合您的喜好,您還可以退回到Theme因此您可以將Activity設置為Dialog ,並將其像Dialog一樣對待,也可以使用DialogFragment

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM