Android Question Wait For sometimes doesnt fire?

techknight

Well-Known Member
Licensed User
Longtime User
Now I could be making a mistake and doing this completely wrong, but sometimes the Wait For doesnt work.

Here is the code I am using:

B4X:
'This routine will verify the authorization for Server Access.
Sub CheckAuthorization As ResumableSub
    Dim AuthSocket As Socket
    AuthSocket.Initialize("AuthSocket")
    AuthSocket.Connect(Address, Port, Timeout)    'Connect to Server
    Wait For AuthSocket_Connected (Successful As Boolean)
    If Successful = False Then
        ToastMessageShow("Unable to connect to the server at this time. Please check your connections and try again.", True)
        ProgressDialogHide  
        Return False    'This routine failed. Lets return a boolean.
    End If
    If AuthSocket.Connected = True Then 'Lets make sure we are still connected to the server.
        AstreamsAuth.Initialize(AuthSocket.InputStream, AuthSocket.OutputStream, "AstreamsAuth")
        AstreamsAuth.Write(("GT " & Account.Username & " " & Account.Password).GetBytes("UTF8"))
        Wait For Auth_complete (Result As Boolean)            'Wait for the data to come back from the socket. (or error)
      
       'Sometimes we dont make it here. The above Wait For event doesnt respond.

        If Result = True Then
            Log("Account Authorized")
            ProgressDialogHide
            Try
                AstreamsAuth.Close
                AuthSocket.Close
            Catch
                Log("Socket closed already")
            End Try
            Return True
        Else
            Log("Account Not Authorized. Reason: " & Account.AuthStatus)
            ProgressDialogHide
            Try
                AstreamsAuth.Close
                AuthSocket.Close
            Catch
                Log("Socket closed already")
            End Try          
            Return False
        End If
    Else
        ToastMessageShow("Unable to connect to the server at this time. Please check your connections and try again.", True)
        ProgressDialogHide  
        Try
            AstreamsAuth.Close
            AuthSocket.Close
        Catch
            Log("Socket closed already")
        End Try
        Return False    'This routine failed. Lets return a boolean.       
    End If
End Sub

Sub AstreamsAuth_NewData (Buffer() As Byte)
    Try
        Dim ResponseString As String = Common.RemoveSpecialCharacters(BytesToString(Buffer, 0, Buffer.Length, "UTF8"))
        #if DEBUG
            Log(ResponseString)
        #End If
        Dim ResponseArray() As String = Regex.Split("\|", ResponseString)
      
        Account.AuthStatus = ResponseArray(0)
      
        'Lets verify the authorization
        If ResponseArray(1) = "1" Then     'We are authorized.
            Account.AuthorizedBots.Initialize
            Account.AuthorizedBots.AddAll(Regex.Split(",", ResponseArray(12)))    'Add all of our bot IDs in the list.
            Account.Expiration = Common.Left(ResponseArray(17), 10)
            Log("Ret: Authorized")  'This works, puts a log in the IDE
            CallSub2(Me, "Auth_Complete", True)  'This doesnt work sometimes. its hit or miss.
        Else    'We are not authorized.
            Account.AuthorizedBots.Initialize
            Account.AuthorizedBots.Clear
            Account.BotID = ""  
            Log("Ret: Not Authorized")
            CallSub2(Me, "Auth_Complete", False)
        End If
    Catch
        Account.AuthStatus = "Incorrect Response from Server"
        CallSub2(Me, "Auth_Complete", False)
    End Try
End Sub

Sub AStreamsAuth_Error
    Try
        ToastMessageShow("Dropped connection to Server. Reason: " & LastException.Message, True)
    Catch
        Log("Error: " & LastException.Message)
    End Try  
    Account.AuthStatus = "Unable to complete login request."
    CallSub2(Me, "Auth_Complete", False)
End Sub

Sub AstreamsAuth_Terminated
    'ToastMessageShow("Dropped connection to Server", True)
'    Account.AuthStatus = "An error has prematurely ended the connection to the server."
'    CallSub2(Me, "Auth_Complete", False)  
End Sub

So above, I am setting up asyncstreams and waiting on a response or a disconnection from the server. Most of the time it works fine. if astream error, terminated, or newdata is fired, I call the Auth_Complete sub which is just a wait-for catch. I dont know if I am doing this right though.

sometimes itll see this catch and resume from the wait for, sometimes not.

any ideas? Thanks.
 

stevel05

Expert
Licensed User
Longtime User
Is the eventname correct in
B4X:
Wait For Auth_complete (Result As Boolean)
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
I see I didnt capitalize it. Does that matter? It works most of the time. Not all the time especially on first install of the App.

Edit: Just capitalized the letter, and it made no difference. On first launch it doesnt work. The subroutines below that one are the event calls.
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
I don't think so, but I can't see where it is defined in your code.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
if astream error, terminated, or newdata is fired, I call the Auth_Complete sub which is just a wait-for catch. I dont know if I am doing this right though.
The call to Auth_Complete in AstreamsAuth_Terminated has been commented out. Therefore, Auth_Complete will only be fired for error and newdata and not for the termination event. At least according to your source posted above.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
The call to Auth_Complete in AstreamsAuth_Terminated has been commented out. Therefore, Auth_Complete will only be fired for error and newdata and not for the termination event. At least according to your source posted above.

I already tried adding something in there and it didnt make any difference. I commented it out originally because if that Event triggers, I cant determine if the connection and authorization was successful or not. I ran into a problem where it fired true, and then false on the same call because the Server will terminate the connection with or without proper authorization. The server is designed to send a reply, and abort the connection.
 
Last edited:
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
There is no case where a wait for was called, the event is raised and the event is not intercepted.

If you have, by mistake, not switched yet to B4XPages then it can happen that the event will not be raised as the activity is paused.

It is not a mistake to have choice and program with or without something that I feel is being encroached on me. So no, I havent used b4xpages yet. I am very slow to adapt to change as change drives me nuts. So it is going to take me a long while before I uproot everything I have done and move onto something like that. If I start writing a new app from scratch then maybe I will mess with it and use it.

Anyways, I digress. Its in a service. not an activity. Plus the activity is front and center when this routine is called, since you have to press the login button for it to work.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is not a mistake to have choice and program with or without something that I feel is being encroached on me.
That's true. You have choice. All methods are supported and will stay supported.
Anyways, I digress. Its in a service. not an activity
It wasn't clear in the first post.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
That's true. You have choice. All methods are supported and will stay supported.

It wasn't clear in the first post.

Yea I may have forgotten that little detail when I looked back at my post. Sorry.

The routine when installing it in debug mode for testing, and first launching of the app, wont fire when I click the login button which invokes the subroutine above. Whats weird is I can hit the restart button in the IDE, then go back and hit login again, it works fine.

I cant seem to figure it out.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Never use CallSub together with Wait For. Use CallSubDelayed. Otherwise the CallSub can be called before the Wait For is called.

To continue my previous recommendation, all of this complexity will disappear once you switch to B4XPages. You will not need to send messages between the activity and service, each one with its own, complicated, life cycle.
All of these challenges simply don't exist.
 
Upvote 0

techknight

Well-Known Member
Licensed User
Longtime User
Never use CallSub together with Wait For. Use CallSubDelayed. Otherwise the CallSub can be called before the Wait For is called.

To continue my previous recommendation, all of this complexity will disappear once you switch to B4XPages. You will not need to send messages between the activity and service, each one with its own, complicated, life cycle.
All of these challenges simply don't exist.

It would probably involve a major rewrite of my apps to do that based on how my apps are designed, Something I dont have the time or money to do right now. We are barely hanging on by a thread, on the verge of going out of business thanks to the pandemic.

Anyways, CallSubDelayed fixed it. I always thought that was for sending from a service back to the activity.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Never use CallSub together with Wait For. Use CallSubDelayed. Otherwise the CallSub can be called before the Wait For is called.
In need to burn that into my "what not to do" eeprom of my brain...
 
Upvote 0
Top