Search code examples
androidonresumeactivity-lifecycle

Android Studio - Activity Life Cycles, On Resume


How can I know whether an activity has entered onResume due to a button being pressed and hence intent started, or if the user selected to navigate back?

EDIT:

  • Basically, Activity A is playing a song

  • You can choose a new song to be played in Activity B, which sends an intent back to activity A to start a new song

  • But at the moment if "back" is pressed from Activity B, I need the song to continue playing, rather than what it does at the moment which is restart as it runs the intent from previuosly in onResume();


Solution

  • When the user navigates from the Activity to another Activity you can use startActivityForResult and set parameters, such as which button is pressed, in the setResult of the new Activity.

    What you cannot do is always know how the user got to onResume since things happen out of your control For example a phone call could background the app, and once it's done, it returns to the foreground.

    You can also use onNewIntent to help with navigation from another Activity that did not start the Activity you are trying to monitor, in cases where you have indirect actions (like Activity A -> Activity B -> Activity C -> Activity A).

    For PendingIntents you can also include data about the launching app/Activity.

    EDIT:

    If you are just trying to put data into an Intent so that when the Activity is launched, then you can use code like:

    Intent intent = new Intent();
    intent.setClass(this, MyActivity.class);
    intent.putExtra("BUTTON_ID", "button_a");
    startActivity(intent);
    

    However, remember that you will need to use onNewIntent if the Activity is already running an a new Intent is sent to the Activity to "start" it. That seems to be the core problem that you are having. However, you also need to "reset" the intent data after consuming it - otherwise if the Activity is resumed without a new Intent then you will still have the old Intent data.