Android Tutorial Android Process and activities life cycle

New video tutorial:



Lets start simple:
Each B4A program runs in its own process.
A process has one main thread which is also named the UI thread which lives as long as the process lives. A process can also have more threads which are useful for background tasks.

A process starts when the user launches your application, assuming that it is not running already in the background.

The process end is less determinant. It will happen sometime after the user or system has closed all the activities.
If for example you have one activity and the user pressed on the back key, the activity gets closed. Later when the phone gets low on memory (and eventually it will happen) the process will quit.
If the user launches your program again and the process was not killed yet the same process will be reused.

A Basic4android application is made of one or more activities. Android support several other "main" components. These will be added to Basic4android in the future.

Activities are somewhat similar to Windows Forms.
One major difference is that, while an activity is not in the foreground it can be killed in order to preserve memory. Usually you will want to save the state of the activity before it gets lost. Either in a persistent storage or in memory that is associated with the process.
Later this activity will be recreated when needed.

Another delicate point happens when there is a major configuration change in the device. The most common is an orientation change (user rotates the device). When such a change occurs the current activities are destroyed and then recreated. Now when we create the activity we can create it according to the new configuration (for example, we now know the new screen dimensions).
How do we handle it? :confused:
When you create a new activity you will start with the following code template:
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
 
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
Variables can be either global or local. Local variables are variables that are declared inside a sub other than Process_Globals or Globals.
Local variables are local to the containing sub. Once the sub ends these variables no longer exist.
Global variables can be accessed from all subs.

There are two types of global variables.
Process variables and activity variables.

Process variables - These variables live as long as the process lives.
You should declare these variables inside sub Process_Globals.
This sub is called once when the process starts (this is true for all activities, not just the first activity).
These variables are the only "public" variables. Which means that they can be accessed from other modules as well.
However, not all types of objects can be declared as process variables.
All of the views for example cannot be declared as process variables.
The reason is that we do not want to hold a reference to objects that should be destroyed together with the activity.
In other words, once the activity is being destroyed, all of the views which are contained in the activity are being destroyed as well.
If we hold a reference to a view, the garbage collector would not be able to free the resource and we will have a memory leak.
The compiler enforces this requirement.

Activity variables - These variables are contained by the activity.
You should declare these variables inside Sub Globals.
These variables are "private" and can only be accessed from the current activity module.
All objects types can be declared as activity variables.
Every time the activity is created, Sub Globals is called (before Activity_Create).
These variables exist as long as the activity exists.

Sub Activity_Create (FirstTime As Boolean)
This sub is called when the activity is created.
The activity is created when the user first launches the application, the device configuration has changed (user rotated the device) and the activity was destroyed, or when the activity was in the background and the OS decided to destroy it in order to free memory.
This sub should be used to load or create the layout (among other uses).
The FirstTime parameter tells us if this is the first time that this activity is created. First time relates to the current process.
You can use FirstTime to run all kinds of initializations related to the process variables.
For example if you have a file with a list of values that you need to read, you can read it if FirstTime is True and store the list as a process variable.
Now we know that this list will be available as long as the process lives and there is no need to reload it even when the activity is recreated.

To summarize, you can test whether FirstTime is True and then initialize process variables.

Sub Activity_Resume and Sub Activity_Pause (UserClosed As Boolean)
Each time the activity moves from the foreground to the background Activity_Pause is called.
Activity_Pause is also called when the activity is in the foreground and a configuration change occurs (which leads to the activity getting paused and then destroyed).
Activity_Pause is the last place to save important information.
Generally there are two types of mechanisms that allow you to save the activity state.
Information that is only relevant to the current application instance can be stored in one or more process variables.
Other information should be stored in a persistent storage (file or database).
For example, if the user changed some settings you should save the changes to a persistent storage at this point. Otherwise the changes may be lost.

Activity_Resume is called right after Activity_Create finishes or after resuming a paused activity (activity moved to the background and now it returns to the foreground).
Note that when you open a different activity (by calling StartActivity), the current activity is first paused and then the other activity will be created if needed and (always) resumed.

As discussed above Activity_Pause is called every time that the activity moves from the foreground to the background. This can happen because:
1. A different activity was started.
2. The Home button was pressed
3. A configuration changed event was raised (orientation changed for example).
4. The Back button was pressed.

In scenarios 1 and 2, the activity will be paused and for now kept in memory as it is expected to be reused later.
In scenario 3 the activity will be paused, destroyed and then created (and resumed) again.
In scenario 4 the activity will be paused and destroyed. Pressing on the Back button is similar to closing the activity. In this case you do not need to save any instance specific information (the position of pacman in a PacMan game for example).
The UserClosed parameter will be true in this scenario and false in all other. Note that it will also be true when you call Activity.Finish. This method pauses and destroys the current activity, similar to the Back button.

You can use UserClosed parameter to decide which data to save and also whether to reset any related process variables to their initial state (move pacman position to the center if the position is a process variable).

A new module is available for handling the UI state: http://www.b4x.com/forum/basic4andr...ging-android-applications-settings-state.html

Now you should be ready for this short quiz:
http://www.b4x.com/android/forum/threads/quiz-12-find-the-bug-process-activities-life-cycle.37899/
Life cycle graphical diagram: http://www.b4x.com/android/forum/threads/graphical-life-cycle-of-a-b4a-activity.40515/

Starting from v5.20 there is a new feature named Starter Service that acts as a single program entry point: https://www.b4x.com/android/forum/threads/starter-service-consistent-single-entry-point.57599/
 
Last edited:

Hennell

Member
Licensed User
Longtime User
I'm finally making the switch to Android, so have been looking over the tutorials and trying to understand how these default subs are called and when; ended up making a flow chart which I think indicates what happens, Erel is this correct or am I still missing something?

Basic4Android process flow chart.
 

mjcoon

Well-Known Member
Licensed User
... In other words, once the activity is being destroyed, all of the views which are contained in the activity are being destroyed as well.
...
Every time the activity is created, Sub Globals is called (before Activity_Create).
These variables exist as long as the activity exists.

Is this neat behaviour wrecked when running under the IDE in debug mode? I ask because I am seeing multiple strings overlaid in a Label in my simple program when I induce a pause/resume. This looks as if multiple instances of the label object are being created and mapped onto the same view. (Not sure if I have the terminology right; I've only just started having another go at B4A!) Edit: No, it was not that; I had wrongly thought I needed to do LoadLayout() at each resume (because the Activity would have been destroyed!)...

Mike.
 
Last edited:

luke2012

Well-Known Member
Licensed User
Longtime User
Finish & Start

It's possible to programmatically finish the current activity and then start another activity ?

Activity.Finish
StartActivity("OtherActivity")
 

luke2012

Well-Known Member
Licensed User
Longtime User
I'm glad to known that!

I was in doubt about this because I believe that the Activity.Finish close the activity and the next statment will not execute.

Thanks for the info Erel!
 

luke2012

Well-Known Member
Licensed User
Longtime User
I understood!
It is also possible to call Activity.Finish within the Activity_Pause event to destroy the activity when I leave it (for example when I start a new activity)?
 

sortec.nick

Member
Licensed User
Longtime User
I understood!
It is also possible to call Activity.Finish within the Activity_Pause event to destroy the activity when I leave it (for example when I start a new activity)?

Yes, but it is also important to bear in mind that Activity_Pause is called in every case that the current Activity loses focus i.e. when the phone display goes to sleep or the user accesses the Settings menu or any other application.

One solution might be to pass a focus token between activities that knows which activities to leave open. You might wish to later make a Breadcrumbs object that tracks movement between activities.
 

luke2012

Well-Known Member
Licensed User
Longtime User
Yes, but it is also important to bear in mind that Activity_Pause is called in every case that the current Activity loses focus i.e. when the phone display goes to sleep or the user accesses the Settings menu or any other application.

One solution might be to pass a focus token between activities that knows which activities to leave open. You might wish to later make a Breadcrumbs object that tracks movement between activities.

What do you mean when you say focus token ?
 

Turbo3

Active Member
Licensed User
Longtime User
Some of my users report losing their setup values. My app reads in a previously saved setup file in Activity_Create when FirstTime=true and the file exists. So at first I did not see how this could be happening. When their setup file is not read in, default settings are used which on exit then overwrite their saved settings.

However, I now see a hole that could explain this happening. The only routine who's code is guaranteed to execute all the way through is Activity_Pause. Code in Activity_Create could get skipped if an orientation change happens while code in Activity_Create is being execute. So there is a race when Activity_Create starts executing and android needing to destroy it because of an orientation change. The majority of the time Activity_Create will finish first. But if not then the next time it starts the FirstTime flag will be false and any code conditioned to execute by FirstTime will not get executed and since it did not get executed (or execute to completion) the first time because of the orientation change it never gets execute.

The solution to this is not to rely on FirstTime to mean that all the code in Activity_Create has been executed but use your own flag set when all the things that need to be done once have completed. If this new flag is not set then the next time Activity_Create is executed do it again until the flag is finally set. The difference is that FirstTime is set when Activity_Create is first called (i.e. at the top of the code) and this new flag you create would be set at the end of Activity_Create signaling all the first time code you need got executed.

I think most people would not need this extra level if their code in Activity_Create is short and fast. But if you are reading in a large setup file you are exposed to being yanked out of it by Android before it completes while at the same time having FirstTime set to true.

Anyway, that is my best guess at what must be happening when a user loses their setup file.
 

Turbo3

Active Member
Licensed User
Longtime User
Just to be clear, so any subroutine called by Activity_Create will also complete before Activity_Pause runs even if that sub reads in a thousand bytes of data from the SD card.
 

corwin42

Expert
Licensed User
Longtime User
Just to be clear, so any subroutine called by Activity_Create will also complete before Activity_Pause runs even if that sub reads in a thousand bytes of data from the SD card.
Yes.

But you shouldn't do this. Only do necessary initialization in Activity_Create and do not load large amount of data. If Activity_Create does not return after a few seconds you will get an ANR (Activity Not Responding) error. Load your data asynchronously.
 
Top