简体   繁体   中英

How to display alert dialog in any activity in android application?

In my application I want to display common AlertDialog for all activities.
In my background thread, Server data is coming periodically.

Now if some user defined criteria are matched with that data, I want to display AlertDialog on screen in any activity which is currently on front.

How can I identify that where to display AlertDialog ?
And if my application is in background, I want to set Notifications rather than AlertDialog .

You will need a Service running in background.

All the needed code is there:

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

Your service will send a broadcast to your Activity. If your activity is not in foreground, nothing will happen.

You can show alert dialog from background by any one of below...

But before your show dialog you need to check if activity is running or not by using one boolean flag as below otherwise you will get 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

You need to show your dialog on UI thread like below...

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. Handler

You can create an handler in Activity Class, and can invoke sendMessage to that handler object. Write code to display alert in handleMessage method of Handler, for Example:

Activity Class

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 thread= new Thread()
{
    public void run()
    {             
         mHandler.sendEmptyMessage(0);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM