Android Question Mqtt service that stop responding when other app are on foreground

amorosik

Expert
Licensed User
B4X:
*** Service (starter) Create ***
2021-09-17 18:38:41 083 - *********************************************
2021-09-17 18:38:41 084 - ************ START OF PROGRAM ***************
2021-09-17 18:38:41 085 - *********************************************
2021-09-17 18:38:41 086 - Starter.Service_Create
** Service (starter) Start **
2021-09-17 18:38:41 172 - Starter.Service_Start
** Activity (main) Create, isFirst = true **
2021-09-17 18:38:41 215 - Main.Activity_Create FirstTime=true
2021-09-17 18:38:41 250 - B4XMainpage.B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
2021-09-17 18:38:41 804 - GET_SAFE_DIR_DEFAULT_EXTERNAL=20099293184
2021-09-17 18:38:41 809 - DIR_ROOT_EXTERNAL=20099293184
2021-09-17 18:38:41 812 - DIR_ASSETS=0
2021-09-17 18:38:41 816 - DIR_DEFAULT_EXTERNAL=20099293184
2021-09-17 18:38:41 820 - DIR_INTERNAL_CACHE=20259725312
2021-09-17 18:38:41 823 - DIR_INTERNAL=20259725312
2021-09-17 18:38:41 825 - SI permesso PERMISSION_READ_PHONE_STATE
*** Service (mqtt) Create ***
2021-09-17 18:38:41 954 - Mqtt.Service_Create
** Service (mqtt) Start **
2021-09-17 18:38:41 971 - Mqtt.Service_Start
*** Service (firebasemessaging) Create ***
2021-09-17 18:38:42 103 - FirebaseMessaging.Service_Create
** Service (firebasemessaging) Start **
2021-09-17 18:38:42 123 - FirebaseMessaging.Service_Start
*** Service (ftpclient) Create ***
2021-09-17 18:38:42 238 - FtpClient.Service_Create
** Service (ftpclient) Start **
2021-09-17 18:38:42 260 - FtpClient.Service_Start
*** Service (gpsservice) Create ***
2021-09-17 18:38:42 293 - GpsService.Service_Create
2021-09-17 18:38:42 297 - GpsService.StartGps
** Service (gpsservice) Start **
2021-09-17 18:38:42 401 - GpsService.Service_Start
2021-09-17 18:38:42 426 - B4XMainpage.B4XPage_Appear
2021-09-17 18:38:42 429 - B4XMainpage.Aggiorna_Display
(SecurityException) java.lang.SecurityException: getDeviceId: The user 10240 does not meet the requirements to access device identifiers.
2021-09-17 18:38:42 822 - SI permesso PERMISSION_RECEIVE_SMS
SI permesso PERMISSION_WRITE_EXTERNAL_STORAGE
2021-09-17 18:38:43 006 - Mqtt.SubscribeToTopics
2021-09-17 18:38:43 025 - Mqtt.ConnectTo: tcp://12.34.56.78:1000
2021-09-17 18:38:43 134 - FirebaseMessaging.SubscribeToTopics
2021-09-17 18:38:43 149 - FtpClient.Inizializza
2021-09-17 18:38:43 157 - GpsService.StartGps
SI permesso PERMISSION_ACCESS_FINE_LOCATION
BatteryTechnology = Li-ion
no extras
=============================================
2021-09-17 18:38:43 303 - Mqtt.EventMqtt_Connected: true
=============================================
Permission Draw Over2: true
2021-09-17 18:39:43 244 - Main.TimerPing_Tick
2021-09-17 18:39:43 268 - Main.TimerGpsInvio_Tick
2021-09-17 18:39:43 374 - GpsService.invia_ping_a_consolle
2021-09-17 18:39:43 386 - GpsService.invia_posizione_gps_a_consolle GPS_SEND=0 LAT:15.19640136 LON:14.28465794 ALT:46 VEL:0.47
2021-09-17 18:39:43 412 - Mqtt.SendMessage
2021-09-17 18:39:43 423 - Mqtt.SendMessage - Inviato Topic=telephone_to_consolle - Payload=COM=PING;TEL=123456789;BAT_LEV=100;BAT_PLU=2;BAT_TEM=336;VER_APP=61;GUID=16E5C1E2-0387-F0AB-D570-43497F98955E;
2021-09-17 18:40:43 236 - Main.TimerPing_Tick
2021-09-17 18:40:43 255 - GpsService.invia_ping_a_consolle
2021-09-17 18:40:43 278 - Main.TimerGpsInvio_Tick
2021-09-17 18:40:43 288 - Mqtt.SendMessage
2021-09-17 18:40:43 297 - Mqtt.SendMessage - Inviato Topic=telephone_to_consolle - Payload=COM=PING;TEL=123456789;BAT_LEV=100;BAT_PLU=2;BAT_TEM=336;VER_APP=61;GUID=1D51E228-A5D1-95D2-521D-C1C0170560E0;
2021-09-17 18:40:43 383 - GpsService.invia_posizione_gps_a_consolle GPS_SEND=0 LAT:15.19646263 LON:14.28464914 ALT:33 VEL:0
2021-09-17 18:40:52 121 - Mqtt.EventMqtt_MessageArrived: Topic=consolle_to_telephone
Payload=x�ca``p���
q
�pt�vtw��Ҷ���z�y�)���0:1/�(?3���58���������������=�������������$i
2021-09-17 18:40:52 124 - Mqtt.EventMqtt_MessageArrived: Payload=COM=START_PACKAGE;PACKAGE=com.anydesk.anydeskandroid;DEST=123456789;GUID=1654343;
2021-09-17 18:40:52 126 - ---------------------------------------------------------------
2021-09-17 18:40:52 128 - GlobRob.esegui_comando_ricevuto
2021-09-17 18:40:52 132 - GlobRob.esegui_comando_ricevuto Comando=START_PACKAGE
2021-09-17 18:40:52 134 - GlobRob.esegui_comando_ricevuto Nome package=com.anydesk.anydeskandroid
No partial wakelock.
2021-09-17 18:40:52 189 - GlobRob.esegui_comando_ricevuto Package avviato => com.anydesk.anydeskandroid
** Activity (main) Pause event (activity is not paused). **
*** mainpage: B4XPage_Disappear [mainpage]
2021-09-17 18:40:52 294 - Mqtt.SendMessage
2021-09-17 18:40:52 299 - Mqtt.SendMessage - Inviato Topic=telephone_to_consolle - Payload=COM=START_PACKAGE;PACKAGE=com.anydesk.anydeskandroid;TEL=123456789;MEZ=5SV;GUID=1654343;
2021-09-17 18:41:43 235 - Main.TimerPing_Tick
2021-09-17 18:41:43 254 - GpsService.invia_ping_a_consolle
2021-09-17 18:41:43 265 - Mqtt.SendMessage
2021-09-17 18:41:43 295 - Mqtt.SendMessage - Inviato Topic=telephone_to_consolle - Payload=COM=PING;TEL=123456789;BAT_LEV=100;BAT_PLU=2;BAT_TEM=336;VER_APP=61;GUID=33D6C651-B981-A6C1-2953-E0887C3CA681;
2021-09-17 18:41:43 390 - Main.TimerGpsInvio_Tick
2021-09-17 18:41:43 401 - GpsService.invia_posizione_gps_a_consolle GPS_SEND=0 LAT:15.19646024 LON:11.28463992 ALT:33 VEL:0.44
** Service (firebasemessaging) Destroy **
2021-09-17 18:41:52 973 - FirebaseMessaging.Service_Destroy
** Service (gpsservice) Destroy **
2021-09-17 18:41:52 994 - GpsService.Service_Destroy
2021-09-17 18:41:52 998 - GpsService.StopGps
** Service (mqtt) Destroy **
2021-09-17 18:41:53 030 - Mqtt.Service_Destroy
** Service (ftpclient) Destroy **
2021-09-17 18:41:53 051 - FtpClient.Service_Destroy
** Service (starter) Destroy (ignored)**
Ignoring event as service was destroyed: eventmqtt_messagearrived
Ignoring event as service was destroyed: eventmqtt_messagearrived
Ignoring event as service was destroyed: eventmqtt_messagearrived
Ignoring event as service was destroyed: eventmqtt_messagearrived


The log transcribed above is the one generated by a gps position tracking program that I wrote
Normally the app always remains in the foreground and works normally by sending and receiving information via mqtt
I recently added a command that allows me to start any package, it is the main app that starts the indicated package
In this case I tried to start Anydesk, obviously it was already installed before, and it shows on the line

2021-09-17 18:40:52 134 - GlobRob.execute_command_received Package name = com.anydesk.anydeskandroid

that the command is executed correctly and the Anydesk screen appears on the phone screen
Since the secondary package is started, and my main app enters in background, after 60 seconds the services (Firebase, Mqtt, Ftp, ...) are interrupted, and therefore the communication channel between the app and the pc is interrupted

The question is: how can i prevent the services from being interrupted and therefore the communication remains active even if my app is 'under' the secondary app that I have just launched?
 
Last edited:

amorosik

Expert
Licensed User
1. Add a foreground service.
#StartAtBoot: True (region attribute)
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS (on Service_Create) ???


2. Implement MQTT in the starter service, or better in one of the B4XPages. B4XPages classes are never paused, while the process is running.
Actually mqtt code is in own service module
Are you advised to place the MQTT code within the standard service Starter module?

service Starter:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

Sub Process_Globals
    Public is_msg_ric As Boolean=False
    Public rp As RuntimePermissions
    Private phone As Phone
    Dim PhoneId As PhoneId
    Dim PE As PhoneEvents
End Sub

Sub Service_Create
    GlobRob.logga("Starter.Service_Create")
 
    Dim rp As RuntimePermissions
    Main.log_dir =rp.GetSafeDirDefaultExternal("App123")
 
    is_msg_ric=False
    CallSubDelayed(Mqtt,"SubscribeToTopics")
    CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")'
    CallSubDelayed(FtpClient, "Inizializza")'
 
    PE.InitializeWithPhoneState("PE", PhoneId)
 
    Try
        CallSubDelayed(GpsService,"StartGps")
        Catch
        GlobRob.Logga("Starter.Service_create - Avvio Service Gps FALLITO => " & LastException)
        End Try
     
    IniFile.scrivi_ini_locale("Ambiente","Ultimo_Avviamento",GlobRob.data_ora_per_log)
End Sub

service Mqtt:
#Region  Service Attributes
    #StartAtBoot: True
    '#StartCommandReturnValue: android.app.Service.START_STICKY
#End Region

Sub Process_Globals
    Private mqtt_client As MqttClient
    Private serializator As B4XSerializator
    Private currentName As String
    Private mqtt_uri As String
    Private mqtt_comando_ricevuto As String
    Public mqtt_connected As Boolean
    Type Mqtt_Message (Body As String, From As String)
End Sub

Sub Service_Create
    GlobRob.logga("Mqtt.Service_Create")
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS
End Sub

Public Sub SubscribeToTopics
    GlobRob.logga("Mqtt.SubscribeToTopics")
    ConnectTo("http://12.34.56.78:12345","123456789")
End Sub

Sub Service_Start (StartingIntent As Intent)
    GlobRob.logga("Mqtt.Service_Start")
    Service.StopAutomaticForeground 'Call this when the background task completes (if there is one)
End Sub

Public Sub ConnectTo(Host As String, Name As String)
    GlobRob.logga("Mqtt.ConnectTo: " & Host & " " & Name)
    currentName = Name
    If mqtt_connected Then mqtt_client.Close

    Try
        mqtt_client.Initialize("EventMqtt", Host, currentName)
        Dim mo As MqttConnectOptions
        mo.Initialize("", "")
        mo.SetLastWill("smartphone/sconnesso", serializator.ConvertObjectToBytes(currentName), 0, False)
        mqtt_client.Connect2(mo)
    Catch
        Log(LastException)
    End Try
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
#StartAtBoot: True (region attribute)
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS (on Service_Create) ???
Not relevant.

Actually mqtt code is in own service module
This works until the service is killed. The Starter service and B4XPages are never killed.
 
Upvote 0
Top