Pregunta

I have 2 activities which are using the same Android task - i.e. they will use the same back stack.

Let's call A the first activity in the back stack, and B the second activity in the back stack.

case 1: A is notified that it goes in the background when A was in the foreground and then B comes in the foreground (for any reason, like because it received an external intent).

case 2: A is notified that it goes in the background when A was in the foreground but another application was started in the foreground.

Question: How does my app differentiate between those 2 cases? Is there a way to know if the transition A in foreground -> A in background keeps the current task displayed on the screen?

Basically, I need to get an event when the Android task becomes visible or invisible.

¿Fue útil?

Solución

If I understand you correctly, your Activity A would do something different if Activity B doesn't get activated after A was paused.

First of all, it's not a good idea to let an activity do something when it's not visible anymore. As we see in the Android lifecycle, it could get stopped: enter image description here

I would put your background code into a service. This service gets notified whenever Activity A or B gets paused or resumed. There you could add a little timeout which has to pass till you start your logic.

If you do that, that would happen:

Case 1: Activity A goes into background and sends a message in the onPause handler to your service. Service starts its timeout timer. Activity B gets started and sends a message in it's onResume handler to the service.

Now the services knows it's still the same activity and acts accordingly.

Case 2: Activity A goes into background and sends the message. The service starts its timeout timer. It timeouts (I think 200ms would be enough) and now your service knows the task isn't active anymore and acts accordingly.

Otros consejos

Use log or Toast in activity life cycle to display message

Keep a static flag in Activity B. set it on resume and unset it on pause.

Override onPostResume

@Override
protected void onPostResume() {

    //Your code here

    super.onPostResume();
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top