Show dialog activity over another app from background

In order to have a dialog activity shown over another application, a few things must be done:

  • The dialog activity must have a translucent theme, to allow the other application to show up behind it (see @android:style/Theme.Translucent.NoTitleBar)
  • The dialog activity must not fill the screen, for the same reason (see Window.setLayout)
  • The dialog activity must be part of a separate task from the base activity, so that it when it is shown above the other application, it does not pull the base activity above the other application as well (see FLAG_ACTIVITY_NEW_TASK)
  • The dialog activity must be brought to the front, so that it is still shown if the activity it is being launched from is running in the background (see FLAG_ACTIVITY_REORDER_TO_FRONT)
  • The dialog activity must show a dialog somehow, e.g. by creating a class which extends the Dialog class directly

In the code that starts the dialog activity:

Intent intent = new Intent(baseActivity, DialogActivity.class);
// NEW_TASK allows the new dialog activity to be separate from the existing activity.
// REORDER_TO_FRONT causes the dialog activity to be moved to the front,
// if it's already running.
// Without the NEW_TASK flag, the existing "base" activity
// would be moved to the front as well.
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(DialogActivity.EXTRA_SOME_PARAM, someParamValue);
// The activity must be started from the application context.
// I'm not sure why exactly.
baseActivity.getApplicationContext().startActivity(intent);

In the above, baseActivity is a reference to the main activity of the application.

It may help to give the dialog activity a launchMode of singleInstance, ensuring that it never accumulates other activities in its task, but this may be unnecessary. The @android:style/Theme.Translucent.NoTitleBar theme allows the activity underneath it to show through.

<activity
    android:name=".DialogActivity"
    android:launchMode="singleInstance"
    android:theme="@android:style/Theme.Translucent.NoTitleBar">
</activity>

For the dialog activity itself, it may be necessary to adjust its window to ensure that it doesn’t fill the whole screen:

 getWindow().setLayout(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.WRAP_CONTENT
);

Likewise, in the dialog activity’s layout XML, it may also be necessary:

android:layout_width="fill_parent"
android:layout_height="wrap_content"

For the dialog itself, you can do a lot of things, but one solution is to extend the Dialog class:

class DialogActivity extends Dialog { ... }

To show the dialog from the activity, just create a new instance of the Dialog and call its show() method.

Leave a Comment