Android Question Having an issue with a service.

Dman

Active Member
Licensed User
Longtime User
I created a service that is supposed to perform a backup of the database in my app every night at 11:30. It performs a backup every night at 11:30 but it also seems to perform one every time I open my app. I would prefer it to only backup once per day.

Here is the code for the service start

B4X:
Sub Service_Start (StartingIntent As Intent)

    Dim hours As Long
    Dim minutes As Long
    Dim nextruntime As Long
        hours = 23
        minutes = 30

    Dim tt As Long
        tt = hours * DateTime.TicksPerHour + minutes * DateTime.TicksPerMinute

    Dim NowDay As Long
        NowDay = DateTime.DateParse(DateTime.Date(DateTime.Now))

    Dim CurrentTime As Long
        CurrentTime = DateTime.Now - NowDay

    If tt > CurrentTime Then
        nextruntime = NowDay + tt
    Else
        nextruntime = NowDay + DateTime.TicksPerDay + tt
    End If

    Log("NextRunTime:" & nextruntime & " Date:" & DateTime.Date(nextruntime) &  "Time:" & DateTime.Time(nextruntime))

    StartServiceAt("",nextruntime,True)

    autoproemail 'This sub zips the database and emails it
End Sub

And here is the code in my main activity. This is where I think the issue is.

B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Load the layout
    Activity.LoadLayout("Menu")

    StartService(Backup)
 

mc73

Well-Known Member
Licensed User
Longtime User
You seem to not have an if condition at your serviceStart. You should call autoproemail only when your dateTime criteria are met and not every time. Another point: why not storing the dateTime of your last back in your db? Then when your service starts, check it, then let backup begin if 24h+ passed, or exit the service by scheduling it for a later time as you already try to do.
 
Upvote 0

Dman

Active Member
Licensed User
Longtime User
OK. I am not sure what I am doing but I will study my code and what you all say and get it figured out. Thanks guys for the direction to look. Y'all are great. :)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can use this code to find the correct schedule time:
B4X:
Sub FindNextTimeInDay(Hours As Int, Minutes As Int) As Long
   Dim ticks As Long
   Dim now As Long = DateTime.Now
   ticks = DateUtils.SetDateAndTime(DateTime.GetYear(now), DateTime.GetMonth(now), _
    DateTime.GetDayOfMonth(now),Hours, Minutes, 0)
   If ticks < now Then
    'skip to tomorrow
    Dim p As Period
    p.Days = 1
    ticks = DateUtils.AddPeriod(ticks, p)
   End If
   Return ticks
End Sub
StartServiceAt(Me, FindNextTimeInDay(23, 30), True)

If the service was started because of a scheduled intent then it will include an extra key named android.intent.extra.ALARM_COUNT.

You can check it like this:
B4X:
If StartingIntent.HasExtra("android.intent.extra.ALARM_COUNT") Then
 'Backup
End If
 
Upvote 0
Top