Android Question StartServiceAtExact

Cristian Achim

Member
Licensed User
Longtime User
Hi,

Can I set a service to run with StartServiceAtExact to every 20 minutes. Something like StartServiceAtExact(Me, TimeToRun, True) and how can I do this?

I tried to verify on three devices and after a short period of time, after application is closed from recent list, the service not start again.

Thank you!

B4X:
Sub Service_Start (StartingIntent As Intent)

Dim Fix, M20, M40, NextHour As Long
Dim Now As Long = DateTime.Now

Dim Per As Period
Per.Hours = 1

Dim NextRun As Int

Fix = DateUtils.SetDateAndTime(DateTime.GetYear(Now), DateTime.GetMonth(Now), DateTime.GetDayOfMonth(Now), DateTime.GetHour(Now), 0, 0)
M20 = DateUtils.SetDateAndTime(DateTime.GetYear(Now), DateTime.GetMonth(Now), DateTime.GetDayOfMonth(Now), DateTime.GetHour(Now), 20, 0)
M40 = DateUtils.SetDateAndTime(DateTime.GetYear(Now), DateTime.GetMonth(Now), DateTime.GetDayOfMonth(Now), DateTime.GetHour(Now), 40, 0)

NextHour = DateUtils.AddPeriod(Fix, Per)

If Now >= Fix And Now < M20 Then
NextRun = DateUtils.PeriodBetween(Now, M20).Minutes + 1
Else If Now >= M20 And Now < M40 Then
NextRun = DateUtils.PeriodBetween(Now, M40).Minutes + 1
Else If Now >= M40 Then
NextRun = DateUtils.PeriodBetween(Now, NextHour).Minutes + 1
End If
    
Dim TimeToRun As Long
TimeToRun = DateTime.TimeParse(DateTime.GetHour(DateTime.Now) & ":" & DateTime.GetMinute(DateTime.Now) & ":00") + NextRun * DateTime.TicksPerMinute

StartReceiver(NTF)

StartServiceAtExact(Me, TimeToRun, True)

Service.StopAutomaticForeground
End Sub
 

Alexander Stolte

Expert
Licensed User
Longtime User
Can I set a service to run with StartServiceAtExact to every 20 minutes. Something like StartServiceAtExact(Me, TimeToRun, True) and how can I do this?
by calling “StartServiceAtExact” as soon as the service has been started by the previous “StartServiceAtExact”.
 
Upvote 0

Cristian Achim

Member
Licensed User
Longtime User
On Android 8 (Samsung Galaxy A6) And Android 12 (Samsung Galaxy S10+) it does not work, work only in Android 14. Some advice please?
 
Upvote 0

Cristian Achim

Member
Licensed User
Longtime User
Hi Erel,

I finished this code two days ago and I tested on five Samsung devices with a service that is running a receiver every hour to 00, 20 and 40 minutes.
After I removed the application from recent list, the situation is:

Galaxy A6 - Android 8 - It works perfectly
Galaxy S10 - Android 12 - It always runs, although there may be a delay of several hours
Galaxy S10+ - Android 12- It always runs, although there may be a delay of several hours
Galaxy S21 Ultra - Android 14 - It works perfectly
Galaxy S24 Plus - Andoid 14 - It works perfectly

Thank you!
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…