Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity Lifecycle: Why is it set to "Paused" and not "Stopped"

To keep me busy during the holidays, I decided to learn about Android Development.

So I'm following the tutorial about an Activity's lifecycle. In the linked article, it says:

During normal app use, the foreground activity is sometimes obstructed by other visual components that cause the activity to pause. For example, when a semi-transparent activity opens (such as one in the style of a dialog), the previous activity pauses. As long as the activity is still partially visible but currently not the activity in focus, it remains paused.

However, once the activity is fully-obstructed and not visible, it stops (which is discussed in the next lesson).

I downloaded the sample app. The sample app has 3 activities, each with buttons that launches the other activity from an Intent. When I clicked "Start B", I expected that Activity A's state should be "Stopped" since it is now fully-obstructed with Activity B's layout. However, it was set to "Paused".

The only time that Activity A's state turns to Stopped is when I click "Start C" from Activity B's layout.

Why is this happening? Is it because of some optimization that is present on newer Android versions or am I misunderstanding the article?

Screenshot

like image 237
Ian Avatar asked Feb 18 '23 00:02

Ian


1 Answers

Here's something I learned the hard way - Google's Android docs are not exactly accurate about everything!

Sometimes, The system optimizes certain behaviors which seem to deviate from the docs. The only way to know exactly how something works is by the hard way - by digging through the source!.

If your app depends on certain system level behaviors such as stopping and pausing to work exactly in a particular sequence as advertised then you will have a hard time. This behavior is controlled by the system and offers no guarantees.

The best way I have found to deal with this is to find out the contract that Google promises the developers and stick to it. For example, In this case, the contract says that if you follow the rules, implementing the required lifecycle callbacks when they are needed, then it will work, and you do not need to know exactly under what circumstances onStop(), onSaveInstanceState(), onPause(),onDestroy() etc are called.

In other words, If you do what is needed to be done when your app is paused by implementing onPause() , Then you don't need to know exactly when your activity will be paused. The pausing/resuming is controlled by the system and is subject to change from version to version (or maybe even from manufacturer to manufacturer if they choose to customize this behavior).

Wish someone had told me this when I had started. It would have saved me a lot of time and frustration. Hope this helps.

like image 152
Anup Cowkur Avatar answered Apr 09 '23 13:04

Anup Cowkur