-2

I'm currently in a class that extends Application and would like to move back to previous activity (or start a new activity) based on another application's status. But I want to switch to another activity in the background and not show the activity to the user. Here's my code:

Intent launchIntent = new Intent(App.this, LoginActivity.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (launchIntent != null) {
    startActivity(launchIntent);
}

I don't want it to get too complex with using Services but just an easy way to achieve what I want to achieve. Is that possible?

waseefakhtar
  • 1,373
  • 2
  • 24
  • 47
  • 1
    I would say that it isn't impossible. One way would be to send some data to your background app(maybe via push notification or IPC or intent) then you can persist those values and when your app comes to foreground you can navigate to the desired screen by fetching those saved values. – Sarthak Mittal Mar 24 '18 at 18:33
  • @SarthakMittal that makes sense. So you suggest I persist some status of the app and when the app comes to foreground, the particular activity launches? – waseefakhtar Mar 24 '18 at 18:37
  • @waseefakhtar yes :) you can create a baseactivity class and override onStart, whenever the app comes to foreground, the onStart will be called and you can handle it from there. – Sarthak Mittal Mar 24 '18 at 18:39
  • 1
    Also, you can handle activity lifecycle from application class. see my answer [here](https://stackoverflow.com/a/49181737/4269149) – Sarthak Mittal Mar 24 '18 at 18:40
  • @SarthakMittal That's brilliant! handling activity lifecycle from Application is what I need! – waseefakhtar Mar 24 '18 at 18:45
  • @waseefakhtar glad I could help :) – Sarthak Mittal Mar 24 '18 at 18:47

1 Answers1

2

You cannot switch to another Activity in the background and not show it to the user because Activity is an android component, that was designed to be shown to the user...

Activity represents the presentation layer of an Android application, e.g. a screen which is visible to the user.

If, perhaps, you want some background (asynchronous) running code, you have a handful of options - Threads, Services, RxJava and other implementations. And though it's not advisable, I recommend starting with AsyncTask. It is a relatively easy way (if not the easiest) of starting/learning doing things in background, although it has some downsides and is not recommended in production code.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52