Android Question Activity.finish not working as expected

mcqueccu

Active Member
Licensed User
I have 2 activities - Main and actPage2. Now I have a condition that when its met, the main activity should end and start the second activity(actPage2).

My problem is the code runs even after Activity.Finish line. The only way it works is when i add return after the activity.finish or use Else for the code below the condition

What am I doing wrong?

Code for the Main activity
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("page1")

    If "A" = "A" Then
        Log("They are the same")
        StartActivity(actPage2)
        Activity.finish
'        Return
    End If
  
    Log("****Am down here***")
    Log(2 + 4)
    Log("********************")
End Sub
Logcat Output
B4X:
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
They are the same     '<-------------------- The condition is true and suppose to finish and start second activity
****Am down here***      '<--------------activity.finish did not work
6
********************
** Activity (main) Pause, UserClosed = true **
** Activity (actpage2) Create, isFirst = true **
** Activity (actpage2) Resume **
 

DonManfred

Expert
Licensed User
This is the expected behaviour. See Android Lifetimecycle tutorial.
Activity.finish is put on the messagequeue. Even the start of the 2nd activity.
The messagequeue runs when the sub finishes.
 

mcqueccu

Active Member
Licensed User
I have seen the Lifetime cycle tutorial. I just need more clarification about the Message Queue

According to the tutorial Here. This is what it says about Activity.finish

This method pauses and destroys the current activity, similar to the Back button.
So to my understanding, I was expecting immediate termination of the 1st Activity and starting the 2nd Activity.

I moved the code to button click event and I still get same output in logs

B4X:
Sub Button1_Click
    
    If "A" = "A" Then
        Log("They are the same")
        StartActivity(actPage2)
        Activity.finish
'        Return
    End If

    Log("****Am down here***")
    Log(2 + 4)
    Log("********************")
    
End Sub

Does it mean that I have to add RETURN after every ACTIVITY.FINISH?
 

Erel

Administrator
Staff member
Licensed User
Activity.Finish sends a message to the message queue. Only when that message is processed will the activity be finished. It will never happen before your current code completes.

This is also true for StartActivity.
 
Top