CommonsWare CommonsWare - 5 months ago 22
Android Question

How Do I Launch the Same Activity Into a Separate Window in Android N Multi-Window?

The docs for the Android N Developer Preview 1 indicate that you can use

Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
to request that Android launch an activity into a separate window (freeform) or an adjacent pane (split-screen). Google's sample code shows using
Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK
to accomplish this.

This works fine, if the activity being started is a different class than the one doing the starting.

So, for example, if you have a
MainActivity
that has the following code to launch a separate instance of itself:

Intent i=
new Intent(this, MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(i);


then the result is that
FLAG_ACTIVITY_LAUNCH_ADJACENT
is ignored and the new activity instance goes into the existing window or pane.

If, however, you launch any other activity (e.g.,
SecondActivity.class
), then
FLAG_ACTIVITY_LAUNCH_ADJACENT
works as advertised.

What if you want to allow the user to open two spreadsheets, two notepads, or two of whatever-it-is from your app? How can we use
FLAG_ACTIVITY_LAUNCH_ADJACENT
to launch two instances of the same activity?

Answer

According to the discussion on this issue, you also need to blend in FLAG_ACTIVITY_MULTIPLE_TASK:

  Intent i=
    new Intent(this, MainActivity.class)
      .setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT |
        Intent.FLAG_ACTIVITY_NEW_TASK |
        Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

  startActivity(i);

Then the two activity instances will be in separate windows/panes/whatever.

This sample project demonstrates this for the N Developer Preview 1.