Android Question Service Start Stop Resume: the stopservice, Cancel the 'startserviceat' previous?

netsistemas

Active Member
Licensed User
Longtime User
when do:
B4X:
Sub Service_Start (StartingIntent As Intent)
    Try
       
        Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS
       
       
           
        flp.Initialize("flp")
        flp.Connect
       
        IniciarGPSPlus

       
       
       
            StartServiceAt(Me, DateTime.Now + Intervalo * 60 * 1000 ,True )

        End If
        Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
    Catch
        Log(LastException)
    End Try
   
End Sub



Sub GPS_LocationChanged (Location1 As Location)
    Try
        LocationUltima = Location1
         Log(Location1)
       
        modGeneral.SetLocation(Location1, ForzarDeteccionGPSXFIREBASE)
        SaveModoYPosicionAndSTOP( ForzarDeteccionGPSXFIREBASE)
        ForzarDeteccionGPSXFIREBASE = False

        StopService(Me)
       
    Catch
        Log(LastException)
    End Try
End Sub



the stopservice, Cancel the 'startserviceat' previous?



i need a service always running (every 10 minuts cath GPS location), and the service are destroyed.
i read a lotof messages in forum, but i can't understand the process

i include in service this cote too:
B4X:
#Region  Service Attributes
    #StartCommandReturnValue: android.app.Service.START_STICKY  
    #StartAtBoot: false
#End Region

and
B4X:
Sub Service_Create
    Try
       
    
        'Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS  'we are handling it ourselves
        lock.PartialLock  
      
        flp.Initialize("flp")
        flp.Connect
      
        IniciarGPSPlus


   
    Catch
        'ToastMessageShow("Service Create: " & LastException.Message,True)
        Log(LastException)
    End Try

End Sub
 

Peter Simpson

Expert
Licensed User
Longtime User
You did study this post didn't you???

You will find that some newer devices will happily run all day long without issues, whilst other are stored by the OS.

I found that Huawei are one of those manufacturers that are extremely aggressive with their Android devices and power saving. Partial lock should have helped you.

Carefully study the code in the link above, actually run the code on your device to see if it stops at all.

BTW what device are you testing your code on???
 
Upvote 0

netsistemas

Active Member
Licensed User
Longtime User
I read the post (i wroten in this post!!! mamamia).
StopService no cancel StartServiceAt.
If you need this (me no) you need do:
CancelScheduledService(Me)

Mi problem is that CONEXION with SQL SERVER are closed and the Serivice have not code to reopen connection.
That is, the service are running, but the conexión are closed. (i think).

Galaxy note 8 and Xiaomi A1
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
Mi problem is that CONEXION with SQL SERVER are closed and the Serivice have not code to reopen connection.
Well for starters you should always close the connection after you have finished with your query or multiple queries.

I always do the following in the exact same order when using SQL databases.
  1. Open the connection to the SQL database server.
  2. Run all my SQL commands.
  3. Only when I'm completely finishes do I close the database again.
  4. I never ever leave a connection open, never.
I'm sure that someone will say that you can leave the connection open, but I like having control over everything that I code, that includes knowing then the database connection is opened and closed.

Actually I have a code module called database, this module is what is used to open and close databases by the rest of the app (other code modules).
 
Last edited:
Upvote 0

netsistemas

Active Member
Licensed User
Longtime User
this is other interesting discusion
i stay the connection open always and i have the control too: alway opened!!!
My aplication have a lot of sentences and consult, the close and reopen may by a delayed for final user.


in any case , thanks for you comment. Now the problem is when restart the phone. The service show but the location and connect are delayed and i continue with this problem..
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
My aplication have a lot of sentences and consult, the close and reopen may by a delayed for final user.
It takes about a 1/10th of a second to open the database if not faster, so that argument of your is null and void. You really should never ever ever ever leave the connection open, it's as simple as that. If need be you can set the inactivity connection timeout to something like 28800 second (which is 8 hours).

If you are using MySQL then I believe that there is a option to set an automatic reconnection on a dropped connection, but I've never set or used that option. If you're using MySQL then you should search Google to find out how to do that, as I've already said you really should not leave connection open.
 
Upvote 0

netsistemas

Active Member
Licensed User
Longtime User
(I use SQL SERVER)
always i read your criterio, but the argument never have been convinced for me.
but i go to change my application. Now, i execute SQL and if there are a error (connection closed), i reopen te conexión.

If i do open, execute sql (or readjdbcResultSet) and close, i need reopen conexion SYNCRONIUS (not asynconouse). I go to tray to do this. (or no... )

My application, when is used, are used like desktop application, and i think this is a good case to keep conexion open. This is a intereseting case to create a new thread.
 
Upvote 0

netsistemas

Active Member
Licensed User
Longtime User
The ERROR located about service, was :

StopService(me) in GPS_LOCATIONCHANGED. The Stop must by do into function that save data in sqlserver not in EVENT

The event, KILL service, and the code into other functions are not executed!!


that is:
B4X:
Sub GPS_LocationChanged (Location1 As Location)
    Try
        LocationUltima = Location1
         Log(Location1)
       
        modGeneral.SetLocation(Location1, ForzarDeteccionGPSXFIREBASE)
        SaveModoYPosicionAndSTOP( ForzarDeteccionGPSXFIREBASE)
        ForzarDeteccionGPSXFIREBASE = False

        'DON'T DO STOPSERVICE HERE, Do into SaveModoYPosicionAndSTOP, this code may be execute BEFORE that the code into SAveModeYPosicionAndSTOP
        'StopService(Me)
       
    Catch
        Log(LastException)
    End Try
End Sub

B4X:
private Sub SaveModoYPosicionAndSTOP(DeteccionGPSXFIREBASE As Boolean)
    Dim TipoCaptura As String     
    Dim Sql As String
    Dim Sql As String
    Try
        
        Log("BASE: SaveModoYPosicionAndSTOP")
        
    
        If CN.SqlConexionOK(True) Then
            
            Log("INIT SP2: SaveModoYPosicionAndSTOP.INSERT")


                
        '        alter  procedure Set_CambioModo(
        '        @Terminal nvarchar(50),
        '        @Latitud As Float,
        '        @Longitud As Float,
        '        @Modo nvarchar(50),
        '        @IsFake Bit,
        '        @CambioEfectuadoPorUsuario As bit,
        '        @AppName nvarchar(10),
        '        @TipoCaptura nvarchar(20),
        '        @FireBase As bit)
        '        As
        '       
            Sql = "Set_CambioModo ?,?,?,?,?,?,?,?,?"
            Dim L As List
            L.Initialize
            
            L.Add(modGeneral.GetAndroidId)
            L.Add(modGeneral.PosicionGPS.Latitud)
            L.Add(modGeneral.PosicionGPS.Longitud)

            
            l.Add(modGeneral.GetModoTXT)
            
            L.Add(modGeneral.IIF(modGeneral.PosicionGPS.IsFake,1,0))
            L.Add(modGeneral.IIF(CambioModoPorUsuario,1,0))
            L.Add("APP1")
            
            
            
            If CapturaXIniApp Then
                CapturaXIniApp = False
                TipoCaptura= "INI APP"
            else If CambioModoPorUsuario Then
                TipoCaptura= "USUARIO"
            ELSE IF DeteccionGPSXFIREBASE Then
                TipoCaptura= "FIREBASE APPLOCAL"
            Else
                TipoCaptura= "Timer"
            End If
            
            L.Add(TipoCaptura)  'tipocaptura
            L.Add(modGeneral.IIF(DeteccionGPSXFIREBASE,1,0))
            
            
            
            
            CN.SqlExecute2(Sql,l,True)
            CambioModoPorUsuario= False
            'cre oque el servicio debe ser destruido tras hacer el insert, por tanto debe ser aqui
            'si se hace en otro sitio, puede ¿no ejecutar este códiog?
            Log("END SP2: doit SaveModoYPosicionAndSTOP.INSERT")

            StopService(Me)
            
        Else
            Log("SaveModoYPosicionAndSTOP.Sin Conexion DB en ServiceTrack ")
            ToastMessageShow("Sin conexión DB(ServiceTrack)",True)
        End If

    Catch
        Log(LastException)
    End Try



    
End Sub
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
What device are you testing it on, make and model???

...
always i read your criterio, but the argument never have been convinced for me.
Well that's your opinion, but nevertheless you're still wrong IMO. You can leave the connection open, but if the connection closes on you and you do not open it again then you will have the issues that you're having.
 
Upvote 0

netsistemas

Active Member
Licensed User
Longtime User
in 2 models: GALAXY NOTE 8 and XIAOMI MI A1 (main Galaxy). (and final users other, but all are testing)
--
My problem has been conceptual. I do not master the services, I hardly know the difference between a serice in background or foregraund, because for me, a service is always in the background (there is no form, so it is background), but I already know that the concept is different.
Regarding the open or closed connection, I have tried to close and open it, and the time, in some cases, especially when working for data, is not acceptable, so I will leave it open, but thanks for making me doubt my decisions. You are aware that they are not the ones that are theoretically correct.
 
Upvote 0
Top