Android Tutorial Android Process and activities life cycle

Discussion in 'Tutorials & Examples' started by Erel, Nov 3, 2010.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Lets start simple:
    Each Basic4android 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:
    Code:
    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.basic4ppc.com/forum/basi...ging-android-applications-settings-state.html

    Now you should be ready for this short quiz:
    http://www.basic4ppc.com/android/fo...-the-bug-process-activities-life-cycle.37899/
    Life cycle graphical diagram: http://www.basic4ppc.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: http://www.b4x.com/android/forum/threads/starter-service-consistent-single-entry-point.57599/
     
    Last edited: Aug 25, 2015
  2. schimanski

    schimanski Well-Known Member Licensed User

    Is it similar to agraham's brilliant threading-lib?

    I want to transform my prime application from windows mobile to android and one of the things I need for this is something like agrahams threading-lib. I have collected data from a server with an own thread and transvered the data over an global variable to the main programm. When the server-thread hangs up, it doesen't have any influence to the main program.
    Have I understand it right, that basic4android is in the future able to manage two independent threads???

    Thanks for your efforts....
     
  3. agraham

    agraham Expert Licensed User

  4. Erel

    Erel Administrator Staff Member Licensed User

    I'll just add that Basic4android has several internal features dedicated for working with multiple threads. For now only the HTTP library uses these features, but I'm sure that in the future there will be several libraries that will use those.
     
  5. schimanski

    schimanski Well-Known Member Licensed User


    Thanks for this information. I think, that android in future is much suitable for my app...
     
  6. agraham

    agraham Expert Licensed User

    It's ready and tested :) waiting for the release of Basic4Android and the creation of the additional libraries forum.
     
  7. schimanski

    schimanski Well-Known Member Licensed User

    Thanks agraham!!!

    That are very great news!!!
     
  8. thanos

    thanos Member Licensed User

    Merry Christmas and a Happy New Year!
    I have a small question.
    I made a simple application with several text boxes and two layout variants included.
    When I change the orientation from one layout to another all the data of the text boxes are dissapear.
    Which activity sub I must call to prevent this data loss?
    Regards

    Thanos
     
    Last edited: Dec 26, 2010
  9. Erel

    Erel Administrator Staff Member Licensed User

  10. DumDroid

    DumDroid New Member Licensed User

    Total Newbie - Layouts

    Hi to all

    I'm a complete Newbie as regards any type of programming.

    I have managed to write a small program with a layout but would like to add another layout as a 'Disclaimer' type dialog that the user has to either Agree/Disagree before the main layout loads. I can work out how to load layouts but can't seem to find in the forums any ways to kill the 2nd layout to leave the main layout active. Or am I looking at this the wrong way?

    Any advice would be helpful.

    Apologies in advance for what may seem a silly question but we all have to learn from scratch sometime!

    DunDroid:sign0013:
     
  11. Erel

    Erel Administrator Staff Member Licensed User

    This is a very good question.
    You can load your second layout into a panel with Panel.LoadLayout.
    Something like:
    Code:
    Sub Globals
     
    Dim pnl2ndLayout As Panel
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
     
    Activity.LoadLayout("firstlayout")
     pnl2ndLayout.Initialize(
    "")
     
    Activity.AddView(pnl2ndLayout, 00100%x100%y)
     pnl2ndLayout.LoadLayout(
    "secondlayout")
    End Sub

    ... later you can remove it by calling:
    pnl2ndLayout.RemoveView
    or you can hide it by setting the visible property to false.
    You will need Core v1.10 or higher for the RemoveView part: http://www.basic4ppc.com/forum/addi...pdates/7106-core-library-updated-v1-10-a.html
     
    valentino s and JohnD like this.
  12. DumDroid

    DumDroid New Member Licensed User

    Layouts - Adding/Removing "on the fly".

    Erel

    I know this is probably not the right thread/forum to mention this but as a Newbie this forum stuff is still a mind field that I'm gradually trying to work out. So I apologise for taking your time but would like to say you're a genius with this stuff!

    Many thanks for solving my problem regarding loading/killing one layout to leave a 2nd in place. As a Newbie, it's not always easy, even after reading help files/forums etc. to understand the answer let alone find the answer! It's even more difficult if you know what you want to do, but don't know what the 'process' is called which means you don't know where to look for an answer! Catch 22.

    I had great fun with B4ppc which I purchased a few years ago and now am trying to learn (from scratch) B4A. Incidentally, I gave up trying to learn Java - I just couldn't get it. So your (better) alternative is a God send!

    Well done on a great piece of software.

    DumDroid:sign0144:
     
    XbNnX_507 and amrimansor like this.
  13. Erel

    Erel Administrator Staff Member Licensed User

    Thank you :)
    The process and activities life cycle is indeed a complex issue which takes time to understand.
     
  14. FrankR

    FrankR Member Licensed User

    Outstanding

    :sign0087:

    Wow - what a great summary at the top of this thread. We all climbed the Android learning curve last year, and it took a whole lot of reading to learn what was summarized here in one outstanding post. Fantastic.
     
  15. Erel

    Erel Administrator Staff Member Licensed User

    Thanks FrankR. This is indeed a very confusing issue.
    A lot of efforts were involved in making it easier for developers to handle the activities life cycle. The whole concept of process (global) objects vs. activity objects is directly derived from this.
     
  16. sultan87

    sultan87 Active Member Licensed User

    Use Sub Process_Globals

    hello
    in a j' activity; initialize 2 variables
    Dim id_Vin_Select As Int
    Dim Type_Trait Ace String
    id_Vin_Select = 5
    Type_Trait = " Modification"
    I would like to recover the contents of these variables in d' other activities how to make?
    Best regards
     
  17. klaus

    klaus Expert Licensed User

    You should declare these variables in Sub Process_Globals.

    Best regards.
     
  18. sultan87

    sultan87 Active Member Licensed User

    Good evening
    here my test

    Main
    '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 var1 As Int
    Dim var2 As String
    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)

    var1 = 15
    var2 = "Démonstration"

    Msgbox ("Main var1 = " & var1,"Suivi")
    Msgbox ("Main var2 = " & var2,"Suivi")

    StartActivity("Act2")

    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub

    Act2

    '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 var1 As Int
    Dim var2 As String

    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)

    Msgbox ("Act2 var1 = " & var1,"Suivi")
    Msgbox ("Act2 var2 = " & var2,"Suivi")

    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub

    in Main the msgbox turns over me var1 = 15 var2 = Demonstration
    in Act2 the msgbox turns over me var1 = 0 var2 =
    I do not understand

    Best regards
     
  19. klaus

    klaus Expert Licensed User

    In the other activities you must call the variables with the module name where they have been declared as a prefix !

    var1 > Main.var1
    var2 > Main.var2

    If you modify these variables in the other activity and want get these values when you come back to the main activity I would suggest you following code:
    Code:
    If FirstTime = True Then
      var1 = 
    15
      var2 = 
    "Démonstration"
    End If
    Best regards.
     
  20. sultan87

    sultan87 Active Member Licensed User

    Hello
    Thank you very
    best regards
     
Loading...