0

I have an android app, which has HomeActivity as the parent activity of all other activities. meaning - I always have an instance of it, and if you press the back button from any activity it will take you to this activity.

Now, there is an option to launch the app from a notification.

When the user clicks the notification, I start RidesActivity (one of the other activites), and in this case if I press back, it closes the app (no instance of HomeActivity).

What can I do in order to start an instance of HomeActivity to the background, and make sure that if the user click back, it will go to HomeActivity?

Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101

1 Answers1

2

Android goes back to the last activity when you press the back button, but at your point there is no last activity, because you directly start the RidesActivity.

To resolve this you can start your MainAcivity via the Intent from the notification instead of your RidesActivity and put some extra information for starting directly the RidesActivity.

Code for your notification:

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //is important to start the activity from a notification
intent.putExtra("startRidesActivity", true);
startActivity(intent);

Code for your MainActivity, onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /*
    * Put the following at the end of this method
    */
    Bundle bundle = getIntent().getExtras();
    if(bundle!=null && bundle.containsKey("startRidesActivity")){
        Intent intent = new Intent(this, RidesActivity.class);
        startActivity(intent);
    }
}

That's it. Now your Notification opens the MainActivity and the MainActivity start directly your RidesActivity. If you click then the back button, you should see your MainActivity and not your homescreen.

Larcado
  • 225
  • 2
  • 10
  • great answer! thanks a lot. just so I know, why is it important to add the NEW_TASK flag when you start activity from notification? in what other cases you need to put this flag? – Ofek Agmon Nov 08 '15 at 10:22
  • It is important, because the notification doesn't run in the context of your app and android need this information to start your app in a "new task". Here it is good explained: http://stackoverflow.com/questions/30886618/android-notification-intent-flag-activity-new-task-required – Larcado Nov 08 '15 at 10:27
  • got it. also, if I get the notification while I am in the app, and I click it - I will have activities in this order: RidesActivity->HomeActivity->any other activities that were running. should I kill all other activities when notification clicked? – Ofek Agmon Nov 08 '15 at 10:30