Android Question Android lifecycle and the back button?

Chris Lee

Member
Licensed User
Hi, I'm just getting to B4A and am going through the usual orientation issues people have with activities.

I have some understanding that activities should have the ability to work independently, but I'm still not clear on a few scenarios.

I have laid out my thought process, but please excuse me if logic is completely flawed.

OK, let’s say I have two activities ActParent and ActChild.

When Main loads ActParent is started.

The User clicks a button in ActParent which opens ActChild.

When the user clicks the back button ActChild will close and they will be returned to ActParent without the need for additional coding.

If they hit the back button again then the app will exit, again without handing code.

So far so good.

Let's say I perform the actions above, but hit the home button while in ActChild.

As stated in the Android lifecycle documentation,

at some point memory cleanup will occur and the application process will no longer be in memory.


Based on what I understand, when I return to the application,

Android may decide to re-load ActChild, since this was the previously loaded activity?


Assuming I write code to check and handle the restoration of applications variables, for example

by using the starter service, then my ActChild will still display correctly.


However what will happen when I hit the back button at this point?


Does ActChild have any knowledge of ActParent, and will the back button attempt to load ActParent, or will it just exit?


If it does just exit how do I handle the back button, or how do I restore the previous state so that the back button will automatically move from ActChild to ActParent?

Another thought is how to test this. How would I force the process to be cleaned from memory to see if my app behaves correctly?

Maybe this could be done by simply running each child activity from main and see if my code will restore state and button navigation.

I'm curious as to how these issues are typically dealt with, and what the B4A best practice is?
 

tigrot

Well-Known Member
Licensed User
Longtime User
To get better control use a similar sub:
B4X:
Sub Activity_KeyPress(KeyCode As Int) As Boolean
   
    If KeyCode = KeyCodes.KEYCODE_BACK  Then
       Return True ' doesn't process "back" 
    End If

End Sub

To let Android behave as usual return false

Ciao
Mauro
 
Upvote 0
Top