Android - How to display a dialog over a native screen? Android - How to display a dialog over a native screen? android android

Android - How to display a dialog over a native screen?


For my application I used an activity with the Dialog theme.You can declare the theme in the manifest file :

<activity android:name="PopupActivity"  android:launchMode="singleInstance" android:excludeFromRecents="true"  android:taskAffinity="" android:theme="@android:style/Theme.Dialog" />
  • use launcheMode="singleInstance" and taskAffinity="" if your popup is detached from your main application. Otherwise user may click the back button and return to the previous activity of your application.
  • excludeFromRecents="true" to avoid your popup to appear in recent tasks (long press home)
  • theme="@android:style/Theme.Dialog" to set the Dialog theme.


How to get the equivalent of launchMode = singleTask in code

I have not seen a clear explanation of how to set these flags programmatically, so I will include my results here. tldr: you have to set FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_MULTIPLE_TASK.

If you launch this directly from your app, your dialog will appear on top of your app's last Activity. But if you use a PendingIntent broadcast by AlarmManager to launch your "dialog", you have time to switch to a different app so you can see that your "dialog" will appear over that other app, if the style is set appropriately to show what is behind it.

Obviously one should be responsible about when it is appropriate to display a dialog on top of other apps.

public class MyReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {// you have to set these flags here where you receive the broadcast// NOT in the code where you created your pendingIntent    Intent scheduledIntent = new Intent(context, AlertAlarmActivity.class);    scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);    context.startActivity(scheduledIntent);