Android Question Service with Class and Socket

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am using a Class and connecting to a TCP Socket within the class.

I am calling this class within a service.

The question I want to know if the class is still connected to the TCP device and I stop the service without closing the TCP socket first, will that crash the app or should it automatically disconnect the socket once the service is closed?
 

aaronk

Well-Known Member
Licensed User
Longtime User
You should close the connection in Service_Destroy.
I was closing the connection in Service_Destroy but not sure if that was causing errors as I have had a heap of ANR crashes and it was related to the connection and not sure if it was due to the connection disconnecting, so I wanted to know if that had anything to do with it.
 

Attachments

  • ANR.txt
    126.3 KB · Views: 123
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
I don't really know how to program in Java, but is there a way that the threading can be added to the attached Library, if so can you add it and compile the Library so I can use it in B4A ?
 

Attachments

  • SSL.zip
    25.3 KB · Views: 92
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
You don't need to know Java.
Use the Threading library to run a sub that closes the socket.
I am guessing you mean this library: https://www.b4x.com/android/forum/threads/threading-library.6775/#content
if so, then I will check it out and see if that helps.

Just so I understand, Is this how you would use it or is this wrong:

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName: Socket Example
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
 
    Dim my_ssl_socket As SocketSSL
    Dim AStreams_ssl As AsyncStreamsSSL
    Dim Thread1 As Thread
    Dim Thread2 As Thread
    Dim Lock1 As Lock
    Dim Lock2 As Lock
 
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)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
 
    If FirstTime Then
        Thread1.Initialise("Thread1")
        Thread2.Initialise("Thread2")
        Lock1.Initialize(True)
        Lock2.Initialize(True)
    End If
 
    Dim args(0) As Object
    Thread1.Start(Null, "ThreadSub1", args)
 
    'Thread2.Start(Null, "ThreadSub2", args) '<< Run this code to disconnect the SSL Socket
 
End Sub

Sub ThreadSub1
    End1 = 0
    Dim Count As Int
    Dim Params(1) As Object
    Do While Count < 1000
        Count = Count + 1
        Params(0) = Count
        end1 = Count
        ok = False
        Do Until ok
            ' this is because Android seems to lose the run message if the user presses back button
            ' this way no message will be ignored
            Thread1.RunOnGuiThread("Update1", Params)
            ok = Lock1.WaitFor(1000)
        Loop
    Loop
End Sub

Sub ThreadSub2
    End1 = 0
    Dim Count As Int
    Dim Params(1) As Object
    Do While Count < 1000
        Count = Count + 1
        Params(0) = Count
        end1 = Count
        ok = False
        Do Until ok
            ' this is because Android seems to lose the run message if the user presses back button
            ' this way no message will be ignored
            Thread1.RunOnGuiThread("Update2", Params)
            ok = Lock2.WaitFor(1000)
        Loop
    Loop
End Sub

Sub Update1(count As Int)
    If my_ssl_socket.IsInitialized = False Then my_ssl_socket.Initialize("my_ssl_socket")
    my_ssl_socket.Connect("192.168.0.100","3051",5000)
    Lock1.Unlock
End Sub

Sub Update2(count As Int)
    my_ssl_socket.Close
    Lock2.Unlock
End Sub

Sub my_ssl_socket_Connected (Successful As Boolean)
    Log("Connected - SSL Socket")
    AStreams_ssl.Initialize(my_ssl_socket.InputStream ,my_ssl_socket.OutputStream ,"AStreams")
End Sub

Sub AStreams_NewData (Buffer() As Byte)

' Data from connection
     Dim msg As String
    Dim cMsg As String
 
    msg = BytesToString(Buffer, 0, Buffer.Length, "ASCII")
    Log("incoming data - " & msg)
 
End Sub

Sub SendData(msg As String)

    Dim Buffer() As Byte
        Buffer = msg.GetBytes("UTF8")

        AStreams_ssl.Write(Buffer)
        AStreams_ssl.Write(Array As Byte(254))
        Log("outgoing data - " & msg)
     
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 
Last edited:
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Hopefully this is what you mean?
Start the SSLSocket like I normally do and connect like I normally do, but use the Thread to close/disconnect the SSLSocket like shown in the code below:

By the way, why wouldn't you connect the SSLSocket with the thread library and only use it to close the socket?

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName: Socket Example
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim my_ssl_socket As SocketSSL
    Dim AStreams_ssl As AsyncStreamsSSL
    Dim Thread1 As Thread
    Dim Lock1 As Lock
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)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    If Thread1.IsInitialized = False Then Thread1.Initialise("Thread1")
    If Lock1.IsInitialized = False Then Lock1.Initialize(True)
 
    If my_ssl_socket.IsInitialized = False Then my_ssl_socket.Initialize("my_ssl_socket")
    my_ssl_socket.Connect("192.168.0.100","3051",5000)
End Sub

Sub my_ssl_socket_Connected (Successful As Boolean)
    Log("Connected - SSL Socket")
    AStreams_ssl.Initialize(my_ssl_socket.InputStream ,my_ssl_socket.OutputStream ,"AStreams")
End Sub

Sub AStreams_NewData (Buffer() As Byte)

' Data from connection
     Dim msg As String
    Dim cMsg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "ASCII")
    Log("incoming data - " & msg)
End Sub

Sub SendData(msg As String)

    Dim Buffer() As Byte
        Buffer = msg.GetBytes("UTF8")

        AStreams_ssl.Write(Buffer)
        AStreams_ssl.Write(Array As Byte(254))
        Log("outgoing data - " & msg)
  
End Sub

Sub ThreadSub1
    End1 = 0
    Dim Count As Int
    Dim Params(1) As Object
    Do While Count < 1000
        Count = Count + 1
        Params(0) = Count
        end1 = Count
        ok = False
        Do Until ok
            ' this is because Android seems to lose the run message if the user presses back button
            ' this way no message will be ignored
            Thread1.RunOnGuiThread("Update1", Params)
            ok = Lock1.WaitFor(1000)
        Loop
    Loop
End Sub

Sub Update1(count As Int)
    my_ssl_socket.Close
    Lock1.Unlock
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Would I be correct with the above code?

And when I want to disconnect the SSL Socket run this code:

B4X:
    ' Only run this code to disconnect the SSL Socket
    Dim args(0) As Object
    Thread1.Start(Null, "ThreadSub1", args)
 
Last edited:
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Oh, Whops.. I was using it in a Activity for testing.

If I was to move the code to a service, would you recommend I connect to the SSL socket in a Thread like how I am closing it, or only close the connection?

Also, what does the Lock actually do? I copied it from a tutorial and couldn't make sense of what it does so I included it in my app.

Is this all I need to do to, or is there something else I need to include:
B4X:
Sub Process_Globals
    Dim my_ssl_socket As SocketSSL
    Dim AStreams_ssl As AsyncStreamsSSL
    Dim Thread1 As Thread
End Sub

Sub Service_Start (StartingIntent AsIntent)
    If Thread1.IsInitialized = False Then Thread1.Initialise("Thread1")
End Sub

' ----------------------------------------------------------
'run this code to disconnect the SSL Socket
Dim Params(1) AsObject
Thread1.RunOnGuiThread("Update1", Params)
' ----------------------------------------------------------

Sub Update1(count As Int)
    my_ssl_socket.Close
End Sub

Would you then do the same as above except use the code to connect to the SSL Socket?
 
Upvote 0
Top