簡體   English   中英

如何在Android應用程序的任何活動中顯示警報對話框?

[英]How to display alert dialog in any activity in android application?

在我的應用程序中,我想為所有活動顯示常見的AlertDialog
在我的后台線程中,服務器數據會定期出現。

現在,如果某些用戶定義的條件與該數據匹配,我想在屏幕上顯示當前正在進行的任何活動中的AlertDialog

如何識別AlertDialog顯示AlertDialog
如果我的應用程序在后台,我想設置Notifications而不是AlertDialog

您將需要在后台運行的服務。

所有需要的代碼都在那里:

http://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/

您的服務將向您的活動發送廣播。 如果您的活動不在前台,則不會發生任何事情。

您可以通過以下任何一個從后台顯示警報對話框...

但是在你的show對話框之前,你需要通過使用一個布爾標志檢查活動是否正在運行,否則你將獲得WindowManager$BadTokenException

// Flag to check if activity is running or not
boolean isActivityRunning = false;

@Override
protected void onResume() {
    super.onResume();
    isActivityRunning = true;
}

@Override
protected void onPause() {
    super.onPause();
    isActivityRunning = false;
}

1. runOnUiThread

您需要在UI線程上顯示您的對話框,如下所示...

runOnUiThread(new Runnable() {
            @Override
            public void run() {
               if(isActivityRunning) {
                 // Your dialog code.
                 AlertDialog ActiveCallDialog = new AlertDialog.Builder(context)
                    .setMessage(R.string.message)                       
                    .setTitle(R.string.title)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
               }    
            }
        });

2.處理程序

您可以在Activity Class中創建一個處理程序,並可以將sendMessage調用到該處理程序對象。 編寫代碼以在Handler的handleMessage方法中顯示警報,例如:

活動類

Handler mHandler = new Handler()
{
    public void handleMessage(Message msg)
    {
       if(isActivityRunning) {
          //Display Alert
          AlertDialog ActiveCallDialog = new AlertDialog.Builder(context)
                    .setMessage(R.string.message)                       
                    .setTitle(R.string.title)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();             
        }            
    }
};

Thread thread= new Thread()
{
    public void run()
    {             
         mHandler.sendEmptyMessage(0);
    }
}

暫無
暫無

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

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