Bring back activity to the top in Android

55 Views Asked by At

I develop android application with launch mode "Single_instance". I want to run an external application from my activity, and bring back my activity to the screen. I'm using Intent.startActivity to run the application, but i'm unable to automatically go back to my activity, and keep external app running in the background. Is there any way to use some flag, to achive this?

I tried to use FLAG_ACTIVITY_PREVIOUS_IS_TOP and Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP, to run external app and put it into the background, but my app doesn't go back to top.

1

There are 1 best solutions below

0
David Wasser On

To do this you'll need to do the following:

  • Launch the external app using startActivity(). This will put the external app in front of your app.
  • Start some kind of timer (post delayed Runnable to Handler or use AlarmManager or something like that) that will wait a certain period of time, enough so that the external app has a chance to start and cover your app.
  • When the timer expires, it should send a local broadcast Intent to a BroadcastReceiver that you create.
  • The BroadcastReceiver should then call startActivity() with a "launch Intent" (you can get one by calling PackageManager.getLaunchIntentForPackage() for your app. This should bring your app back to the foreground in whatever state it was in.

I have found that this will only work if you call startActivity() from a BroadcastReceiver or Service Context, and not from an Activity Context (which is why the extra step of involving the BroadcastReceiver. see. https://stackoverflow.com/a/29769255/769265 and the comment thread for more info on this problem.

There may be problems with this in modern Android versions, as there are strict limitations of how/when code running in the background can launch activities (this is to prevent background processes from disrupting the user). If this doesn't work you probably won't be able to do it at all.

I wrote this off the top of my head and hope that it is understandable.