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:

Witold Giejsztowt

New Member
Licensed User
Longtime User
Hi,

New guy here.
In Main module I am declaring Process_Globals variable.
What happens when I re-declare the same name variable in different activity module Process_Globals Sub ?
 

MrKim

Well-Known Member
Licensed User
Longtime User
Along these lines here is where a little tutorial would be most helpful.
We have activity. code, class, and service modules
Who can access what? And When?
Who can run what? And when?
 

svk123

Member
Licensed User
Longtime User
Can a Activity be cloned or copied? Is it possible to dynamically create new activities (forms) from code?
 

svk123

Member
Licensed User
Longtime User
No. Each activity must be declared in the manifest file. However you can implement most of the activity logic in a class and then reuse this class from multiple activities.

Can Views such as ScrollView, Panel, Buttons, EditTexts be declared in the class which can be reused from multiple activities?
 

ilan

Expert
Licensed User
Longtime User
i have a question, if i exit my actvity and in activity_pause i have activity.finish then the activity will create it self in the next start
but if i exit the activity and i dont want to destroy it and i use the back button

after i return to the activity i have only a blank screen, the layout is not loaded.
what should i do to prevent it

the thing is that i dont want to close the main activity with activity.finish because i am using the paramters in Process_Globals of the main activity

that means: in activity 2 i am changing parameters in Process_Globals of the main activity so main activity can not be finished

all other acitivies i am using activity.finish in the pause event but if i use the back key in the main and return to my app its sows only a black screen

why?
 

ilan

Expert
Licensed User
Longtime User
ok i want to understand,

so activity.finish should be called from a button for example and in the pause event i am saving data or whatever i want to do before the activity will be finished

should i also finish the main avtivity if i want to go to other activities?

the problem is that i want to use parameters that are in the main activity and change them, can i do that also if the main activity is called with activity.finish??

and why afte ri press in main screen the back button and i exit my application when i return i get a blank screen??

if the activity will be destroyd with the back button it should recreate it self on the next start and load the layout file etc...
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
hould i also finish the main avtivity if i want to go to other activities?
Only if you want to remove it from the activities stack.

the problem is that i want to use parameters that are in the main activity and change them, can i do that also if the main activity is called with activity.finish??
If you are accessing process global variables then yes.

and why afte ri press in main screen the back button and i exit my application when i return i get a blank screen??
See this quiz: http://www.b4x.com/android/forum/threads/quiz-12-find-the-bug-process-activities-life-cycle.37899/

It covers several common mistakes.
 

ilan

Expert
Licensed User
Longtime User
the problem is that if i exit my app via home button and return to it everything is ok
but via the back button and return the layout is not loaded and i see a black empty screen

is this a bug? why via the homebutton the app load the activity layout again but via the back button not

but i do to solve the problem is i caught the back button and call ExitApplication but is this the right way ?
 

ilan

Expert
Licensed User
Longtime User
no not only if firsttime is true.
could it be the phone? Samsung 2? because i can create a very simple app with a layout that has 1 button and it does the same
if i exit the app with the back button when it returns i see black screen

i will make a video when i get home and show you
 

ilan

Expert
Licensed User
Longtime User
Would be better if you show us the code than a video on the problem. Without the code we can only guess what you have done wrong.

ok

this is the main activity (its only loading my logo and then start activity menu)

B4X:
#Region  Project Attributes
    #ApplicationLabel: Ninja Hop
    #VersionCode: 13
    #VersionName: 1.42
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: landscape
    #CanInstallToExternalStorage: False
    #AdditionalRes: C:\Android SDK\extras\google\google_play_services\libproject\google-play-services_lib\res, com.google.android.gms
#End Region

#Region  Activity Attributes
    #FullScreen: true
    #IncludeTitle: false
#End Region

'Activity module
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim t1 As Timer
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.
Dim img As ImageView
Dim a1 As Animation
Dim x As Int
Dim y As Int

End Sub

Sub Activity_Create(FirstTime As Boolean)
   
    If FirstTime = True Then
    img.Initialize ("img")
    img.Bitmap = LoadBitmap(File.DirAssets , "pro2.png")
    img.Gravity = Gravity.FILL
   
Activity.Color = Colors.White
   
    y = (Activity.Height / 2) - 38dip
    x = (Activity.Width / 2) - 100dip
   
    Activity.AddView (img, x,y, 200dip ,76dip )

   
    t1.Initialize ("t1", 2000)

    a1.InitializeAlpha("",0,1)
    a1.start(img)
    a1.Duration = 1500
    a1.RepeatCount = 0
    'a3.RepeatMode = a3.REPEAT_REVERSE
   
    t1.Enabled = True
   
    End If

End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean 'Return True to consume the event

If KeyCode = KeyCodes.KEYCODE_BACK Then                                   
        Return True                                                         
    Else
        Return False
    End If

End Sub

Sub t1_tick
t1.Enabled = False
StartActivity(menu)
End Sub


Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
Activity.Finish
End Sub

activity menu i load the layout (not if firsttime = true )

and when i exit my app via the back button = black screen, Home button is ok only back button

 

ilan

Expert
Licensed User
Longtime User
The timer is never enabled when FirstTime is false.

this is what i want, the timer will start after 2 seconds and start activity menu (and will finish activity main)
so it should run only on firsttime

do you know why do i get the black screen? via the back button but home button is ok?
 
Last edited:
Top