Android Question The chat_B4A.ZIP program goes into the background and closes automatically after a few minutes

cxdzbl

Active Member
Licensed User
This is the expected behavior as it doesn't do anything special to run in the background.

Running in the background: Creating a sticky service - long running background tasks
I used this method, Service.StartForeground, but server was still killed about 5 minutes after the cell phone was turned off the screen. The function I want is that server always runs because it needs to receive push information (for example, chat). Thank you
 
Upvote 0

cxdzbl

Active Member
Licensed User
All sorts of methods are used, still can not do? Here's my service code:



B4X:
#Region  Service Attributes
    #StartAtBoot: true
    #StartCommandReturnValue: android.app.Service.START_STICKY
    #ExcludeFromLibrary: True
#End Region


Sub Process_Globals
    Private client As MqttClient
    Private const port As Int =21043
    Private serializator As B4XSerializator
    Public connected As Boolean
'    Type Message (Body As String, From As String)
    Private users As List
    Private currentName As String
    Dim sounds,sounds2 As SoundPool
    Dim bounceId ,bounceId2 As Int
    Dim PhoneWakeState As PhoneWakeState
End Sub

Sub Service_Create
    Dim PhoneWakeState As PhoneWakeState
    PhoneWakeState.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)

    Dim tz As Notification
    tz.Initialize
'    tz.Icon="icon"
    tz.Notify(0)
    Service.StartForeground(0,tz)

    users.Initialize
    sounds.Initialize(1)
    bounceId = sounds.Load(File.DirAssets, "Mes.wav")
    sounds2.Initialize(1)
    bounceId2 = sounds2.Load(File.DirAssets, "7841.wav")

    currentName = "ycwx"'Name
    Dim Host As String="m13.cloudmqtt.com"
    client.Initialize("client", $"ssl://${Host.Trim}:${port}"$, "ycwx" & Rnd(1, 10000000))
    Dim mo As MqttConnectOptions
    mo.Initialize("rykciawl", "82eatOiu9Dq")
    'this message will be sent if the client is disconnected unexpectedly.
    mo.SetLastWill("all/disconnect", serializator.ConvertObjectToBytes(currentName), 0, False)
    client.Connect2(mo)
End Sub

Private Sub client_Connected (Success As Boolean)
    ToastMessageShow($"Connected: ${Success}"$,True)
    If Success Then
        connected = True
        client.Subscribe("all/#", 0)
        client.Publish2("all/connect", serializator.ConvertObjectToBytes(currentName), 0, False)
'        StartActivity(Chat)
    Else
        ToastMessageShow("Error connecting: " & LastException, True)
    End If

End Sub

Private Sub client_MessageArrived (Topic As String, Payload() As Byte)
    Dim receivedObject As Object = serializator.ConvertBytesToObject(Payload)
'    ToastMessageShow(receivedObject,True)
    If Topic = "all/connect" Or Topic = "all/disconnect" Then
        Dim newUser As String = receivedObject
'        ToastMessageShow( "newname:"&CRLF&Topic&":"&newUser,True)
        Dim index As Int = users.IndexOf(newUser)
        If Topic.EndsWith("connect") And index = -1 Then users.Add(newUser)
    Else if Topic = "all/users" Then
        Dim newUsers As List = receivedObject
        CallSubDelayed2(Chat, "NewUsers", newUsers) 'this will start the chat activity if it wasn't started yet.
    Else if Topic = "all/live_xx1" Then
        Dim m As Message = receivedObject
        sounds.Play(bounceId, 1, 1, 1, 0, 1)
        CallSub2(Chat, "NewMessage", m)
        ToastMessageShow("NewMessage1:"&CRLF&m.From&": "&m.Body ,True)
    End If
End Sub

Public Sub SendMessage(topic As String,Body As String)
    If connected Then
        client.Publish2("all/live_xx"&topic, CreateMessage(Body), 0, False)
    End If
End Sub

Public Sub Disconnect
    If connected Then client.Close  '
End Sub

Private Sub CreateMessage(Body As String) As Byte() '
    Dim m As Message
    m.Initialize
    m.Body = Body
    m.From = currentName
    Return serializator.ConvertObjectToBytes(m)
End Sub

Private Sub client_Disconnected
    connected = False
    sounds2.Play(bounceId2, 1, 1, 1, 0, 1)
    
End Sub


Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy
    Disconnect
    ToastMessageShow("stopservice",True)
End Sub
Are you calling Service.StartForeground?
 
Last edited:
Upvote 0

cxdzbl

Active Member
Licensed User
The icon is needed. Keep it.

Does it still disconnect after the screen is turned off? What happens if you don't turn off the screen and keep it on with PhoneWakeState.KeepAlive?

1, I set the icon, mainly service killed a few minutes after the screen closes.
2, the use of SetExactAndAllowWhileIdle (Time, ServiceName) this method, can only guarantee that the screen is re opened, access to the program can automatically connect, but the same can not guarantee in the background has been to maintain connectivity.
B4X:
Sub SetExactAndAllowWhileIdle (Time As Long, ServiceName As String)
    Dim p As Phone
    If p.SdkVersion <23 Then
        StartServiceAtExact(ServiceName, Time,True)
    Else
        Dim in As Intent
        in.Initialize("","")
        in.SetComponent(Application.PackageName &"/."&  ServiceName.ToLowerCase)
        Dim ctxt As JavaObject
        ctxt.InitializeContext
        Dim am As JavaObject= ctxt.RunMethod("getSystemService",Array("alarm"))
        Dim pi As JavaObject
        pi = pi.InitializeStatic("android.app.PendingIntent").RunMethod("getService", _
        Array(ctxt,1,in,134217728))
        am.RunMethod("setExactAndAllowWhileIdle",Array(0, Time, pi))
    End If
End Sub
 
Upvote 0
Top