Android Question Service in Background slowdown problem

uniplan

Active Member
Licensed User
Longtime User
Hi, i created a service that working in background mode.
It strating at boot (i added this parameter) : #StartAtBoot: True

i have a timer that every 10 seconds make 10 pings to ten different ip (saved into my sqlite db), but during my navigation inside the app, i know a
slowdown problem.

I read that the service working in background and don't go to influence the activity.
Why i have this problem?
You can help me ?

this is my code...

B4X:
#Region  Service Attributes
    #StartAtBoot: 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.
    Private timer_ip_check As Timer

    Dim snotif As Notification
End Sub

Sub Service_Create
Try
    fp.inizializza_sql
        
Catch
    Log(LastException)
End Try
End Sub

Sub Service_Start (StartingIntent As Intent)   

    snotif.Initialize
    snotif.Icon = "icon"
    snotif.Sound = False
    snotif.Vibrate = False
    snotif.SetInfo2("Server-control","è in esecuzione",0,Main)
    
    Service.StartForeground(1,snotif)

    timer_ip_check.Initialize("timer_ip_check",15000)
    timer_ip_check.Enabled=True
    
End Sub

Sub Service_Destroy

End Sub


Private Sub timer_ip_check_Tick()
    If fg.CheckConnessione="OK" Then
        carica_ip_da_analizzare

    Else
        fp.scrivi_log("Ip-check non eseguito per mancanza di connessione","Q2","Service_Start")
        notifica_ping_offline("Sei",100,"Connettersi ad una rete")
    End If
End Sub

Sub carica_ip_da_analizzare()
    Try
        
    Dim str_sql_loc As String

    str_sql_loc = ""
    str_sql_loc = str_sql_loc  & "select * "
    str_sql_loc = str_sql_loc  & "from ip_controllo "
    str_sql_loc = str_sql_loc  & " order by id "
    
        
    Dim cursor1 As Cursor

    cursor1 = Main.SQL1.ExecQuery(str_sql_loc)
    If cursor1.RowCount > 0 Then
            timer_ip_check.Enabled=False
    End If
    For i = 0 To cursor1.RowCount - 1
        
        cursor1.Position = i
        Dim id As Int = cursor1.GetInt("id")
        Dim ip As String  = cursor1.GetString("ip") & ""
        Dim descrizione As String   = cursor1.GetString("descrizione") & ""
        Dim intervallo_check As Int= cursor1.GetInt("intervallo_check") & ""
        Dim timeout As Int= cursor1.GetInt("timeout")
        Dim data_ultimo_ping As Long   = cursor1.GetLong("data_ultimo_ping")
        Dim num_ping As Int = cursor1.GetInt("num_ping")
        Dim status As String = ""
        Dim media As String = ""
        
        Dim data_now As Long = DateTime.Now
        Dim dif As Long = data_now - data_ultimo_ping
            
        Dim intervallo_tics As Long = intervallo_check * 1000   
        
        If intervallo_check <> 0 Then
        'ping configurato       
        
        If dif > intervallo_tics Then
            'faccio il ping
            Log("VERIFICO: " & ip)
            Dim res As String = Ping(ip, "Report", num_ping, timeout, True)
                If res <> "Offline"  Then
                    status="Online"
                    Dim sf As StringFunctions
                    sf.Initialize
                    Log("Risposta")
                    Dim linee As List = sf.Split( res,CRLF)
    
                    For i = 0 To (linee.Size -1)
                        Dim linea_singola As String =  linee.Get(i)
                        
                            If linea_singola.Contains("rtt")  Then
                                Dim linee_rtt As List = sf.Split(linea_singola,"=")
                                Dim linee_rtt_uguale As List = sf.Split(linee_rtt.Get(1),"/")
                                media= linee_rtt_uguale.get(1)
                            End If
                    Next
                Else
                    media=""
                    status="Offline"
                    notifica_ping_offline(ip,id,descrizione)
            End If
            
                Dim ultimo_ping As Long = DateTime.Now
                Dim data_ora_loc As String = fg.get_data_str(DateTime.Now,"dd/MM/yyyy HH:mm:ss")
                Dim id As Int = cursor1.GetInt("id")
                Dim str_sql As String = ""
                str_sql = " update ip_controllo set data_ultimo_ping = ?,stato = ?,risposta = ?, media = ?,data_ultimo_ping_string=? where id = ?"
                Main.SQL1.ExecNonQuery2(str_sql,Array As Object(ultimo_ping,status,res,media,data_ora_loc,id))
            
            
                    
        End If
        
        End If

    Next
        cursor1.Close
    
    
    Catch
        Log(LastException)
    End Try
    
    timer_ip_check.Enabled=True
End Sub



'ResultsType: Report, Summary, Status
Sub Ping(URL As String, ResultsType As String, Attempts As Int, Timeout As Int, Message As Boolean) As String

   Dim sb As StringBuilder
   Dim p As Phone
   Dim Option As String = ""
               
   sb.Initialize
                   
   If Message Then

       'ProgressDialogShow("Pinging " & URL)
                 
       DoEvents
       DoEvents
               
   End If

   If ResultsType = "Report" Then   Option = "-v "
   If ResultsType = "Summary" Or ResultsType = "Status" Then Option = "-q "

   p.Shell("ping -c" & Attempts & " -W" & Timeout & Option & URL, Null, sb, Null)
           
   ProgressDialogHide

   If sb.Length = 0 Then Return "Offline"
               
   If ResultsType = "Status" Then
               
       Return "Online"
                           
   Else
               
       Return sb.ToString
                       
   End If

End Sub

Sub notifica_ping_offline(ip As String , id As Int,descrizione As String )
            
    Dim n As Notification
    n.Initialize()
    n.Icon = "icon"
    Dim titolo_push As String = ip & " OFFLINE"
    Dim messaggio_push As String ="" & descrizione
    Dim id_notifica As String = "" & id
        
    n.SetInfo2(titolo_push,messaggio_push,id_notifica,Main)
    n.Notify(id_notifica)
    n.Vibrate=True
    n.AutoCancel=True
End Sub
 

XbNnX_507

Active Member
Licensed User
Longtime User
I read that the service working in background and don't go to influence the activity.
Services code runs in the Main Thread so it does influence the activity ui.

p.Shell("ping -c" & Attempts & " -W" & Timeout & Option & URL, Null, sb, Null)
calling shell will block the main thread until the ping is done meaning it will freeze you activity.

you can use the thread library not advisable by Erel but if you NEED to call shell with long interval ping then it's no other way.


 
Upvote 0

uniplan

Active Member
Licensed User
Longtime User
Why it's advisable by Erel?

There is a methos that i can make (for example) 10 ping without waiting the response by activity?
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
If you can you should avoid the threading library. An important concept in B4A is that the code runs on the main thread.
The problem in this case is in the phone library. It should have executed the command in the background and raise an event when the operation completes.

You will need to use the Threading library here.
 
Upvote 0

uniplan

Active Member
Licensed User
Longtime User
The problem then is the Phone Library.
If i use the Android Studio and java code ,I should not have this problem, right?
 
Upvote 0
Top