Search code examples
androidlifecycle

Distinguishing between different Activity transitions


I have an Activity that plays some audio from within a ListActivity. The user can also click on the list item and go to a more detailed view of that data. I want the audio to keep playing during that transition from one activity to another and keep playing once the detail activity is active BUT I also need to pause the audio if my activity is being paused or stopped for any other reason.

My issue is that I currently pause the audio in onPause() in the ListActivity because I want the audio to be paused when the user navigates away from my activity. E.g. when they press Home or Back. However, I don't want the audio to pause when my detailed view activity gets started. onPause() is called in both instances, so how can I distinguish between the two cases?


Solution

  • Shouldn't you be doing that in a service instead? Wouldn't it be easier? Then you can stop the service when one or another activity is pausing or exiting (depending on which one you want). You could also check if it's started, and stop accordingly whenever you want.

    Or sorry if I didn't understand your question. I see you have a lot of points here on SO, so perhaps I'm just confused.

    --- edited since your third comment:

    1. A Intent to B: send Intent with name of music.
    2. B onCreate: get name of music from Intent. Set flag x to true.
    3. B onResume: start playing music if from A or resumes from last known position if resuming from B.
    4. B back button: override and set x to false. Actually, you'd cover all points where your activity finishes.
    5. B onPause: stop the music if(x), store last known position of music in memory and stop service.

    Here I assume that you want music to keep playing even when returning to A (that's what you said, that's the problem), not just up to B. Setting x is important early on, IMO, because if any other activity (phone call, anything) appears, activity will stop playing the music immediately (user expects that) on onPause. According to Android guidelines, you know that you're getting back to A only if user presses back button or if you finish() your activity. You can fine tuning checking the position of activities in your task (don't remember how to do that right now).

    Personally, I also wouldn't want to resume playback on A (say, B->call->home->A, applying step 3 to A, too), because a disruption in the logical flow of things happens there.

    CAVEAT: I would make sure that there is no other way. I would try to see if you can 1) know in advance which activity is about to be displayed. 2) get any music service to hook up to your task (is that even possible?).

    Anyway, just use my solution if you can't find a clever way to do that. That would be my suggestion. Good luck.