How can I display a dialog on Currently visible activity on android?
Try this if it helps you:
1. Create a Activity
with transparent theme and no title
.
2. In onCreate()
define your alert dialog
.
3. Starting this activity from broadcastReceiver will show the alert dialog
.
Simply you can create an Activity
and set its theme to Dialog
in manifest
like this :
<activity
android:name="Dialog_MsgBox"
android:launchMode="singleInstance"
android:theme="@android:style/Theme.Dialog" >
</activity>
also set launchMode
to singleInstance
to prevent multiple instance of activity.
use whatever layout you want to use for your dialog.
To set different messages, put extra string messages and get them at you Dialog(activity) start up.
Not the best solution but it worked for me..
I created an abstract class MyActivity which extends Activity and placed the setter calls in side OnResume and OnPause of this class. All other activities of my Application simply extend this Custom super class instead of Activity.
Then I created a variable of this class in Application class,
private Activity currentOnTopActivity;
I set/reset this variable inside onResume()
and onPause()
of MyActivity class.
That done, Whenever I want to show a Dialog to the user, I just do following...
if (currentOnTopActivity!=null && !currentOnTopActivity.isFinishing()) {
currentOnTopActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
String msg = "Some msg";
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(currentOnTopActivity);
AlertDialog invitationDialog = null;
// set title
alertDialogBuilder.setTitle("Title ");
// set dialog message
alertDialogBuilder.setMessage(msg).setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something }
});
// create alert dialog
invitationDialog = alertDialogBuilder.create();
// show it on UI Thread
invitationDialog.show();
}
});
}
Intdroducing a Super Activity class also gives me the flexibility to place common code in this abstract class instead of duplicating that in every other Activity.