Android Question ServiceStartAt sometimes doesn't work

Azam Memon

Member
Licensed User
I have created 3 services, named as "Starter", "opener" and "closer". Starter service takes "start_time" and "stop_time" from database and schedule "opener" and "closer" services. I am repeating "Starter" service every one minute to schedule "opener" and "closer" to upcoming time.

The code in "Starter" service, read "start_time" and "stop_time" and schedule "opener" and "closer" with upcoming time, means time which is greater than NOW but lowest from all other start_time and stop_time values in the database.

My sample code of starter is:

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

Sub Process_Globals
    Dim sql As SQL

    Dim next_sch_checker As Long = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59")
    Dim next_sch_checker_end As Long = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59")
   Dim dbname As String = "db.db"
End Sub

Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)
    Dim tm As Long = 0
    Dim tm_end As Long = 0

    next_sch_checker = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59")
    next_sch_checker_end = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59")

    StartServiceAt(Me, DateTime.Now + DateTime.TicksPerMinute, True)

   If File.Exists(File.DirInternal, dbname) Then
        sql.Initialize(File.DirInternal, dbname, False)

        cur = sql.ExecQuery("SELECT * FROM schedule")

       For i=0 To cur.RowCount-1
           cur.Position = i
           tm = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), cur.GetString("start_time"))
           tm_end = DateTime.DateTimeParse(DateTime.Date(DateTime.Now), cur.GetString("stop_time"))
   
           If((tm >= DateTime.Now) And (next_sch_checker >= tm)) Then
               next_sch_checker = tm
           End If
                   
           If((tm_end >= DateTime.Now) And (next_sch_checker_end >= tm_end)) Then
               next_sch_checker_end = tm_end
           End If
       Next

       If next_sch_checker <> DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59") Then
           
           StartServiceAtExact(opener, next_sch_checker, True)
       End If

       If next_sch_checker_end <> DateTime.DateTimeParse(DateTime.Date(DateTime.Now), "23:59") Then
            StartServiceAtExact(closer, next_sch_checker_end, True)
           
        End If

       StartServiceAt(Me, (DateTime.Now + DateTime.TicksPerMinute), True)

End Sub

The problem is, sometimes "opener" and "closer" both the services execute on their specified time but sometimes one of them execute at its specified time but other don't. Is there anything wrong with my code?
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…