Android Question Starting a service every 15 minutes.

Discussion in 'Android Questions' started by rleiman, Dec 23, 2017.

  1. rleiman

    rleiman Well-Known Member Licensed User

    Hi Everyone,

    I would like to wake up a service in 15 minute intervals and continue to do that constantly. For example, if the user pressed a button to start it and the current time is 11:05, I would like the service to wake up at 11:15, 11:30, 12:00 and so on.

    I was thinking about maybe using multiple StartServiceAtExact statements but that would be a lot of them. Is there an easy way to set this up?

    Please show some coding samples I would need.

    Thanks.
     
  2. ilan

    ilan Expert Licensed User

    what are you doing with that service?
    i would not install an app that start a service every 15 minutes.
    maybe it can be solved in a different way
     
    Multiverse app likes this.
  3. rleiman

    rleiman Well-Known Member Licensed User

    Hi Ilan,

    I want to play a sound every 15 minutes but it has to be run on each quarter. I also want to make sure Android doesn't kill it since it needs to run in the background.
     
  4. ilan

    ilan Expert Licensed User

    does the app run always? if it should play a sound every 15 minutes i would use a sticky service.
     
  5. rleiman

    rleiman Well-Known Member Licensed User

    Hi Ilan,

    Yes. It will be running all the time. I can set up a timer to make the sounds play every 15 minutes.

    Can you show some coding samples on setting up the sticky service?

    Thanks.
     
  6. Peter Simpson

    Peter Simpson Expert Licensed User

    Service Attributes had the sticky service.
    I wouldn't use a timer, just use StartServiceAt to start the service every 15 minutes as it is more reliable and the correct way to do it.

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

    'SERVICE START
    Sub Service_Start(StartingIntent As Intent)
        
    'SELECT ONE OF THE FOLLOWING LINES TO USE
        'Either
        StartServiceAt(Null, TimeToNextMinute, True'15 minutes to the nearest whole minute
        'Or
        StartServiceAt(NullDateTime.Now + 900 * 1000True' 900 seconds/60 = 15 minutes from the current second
    End Sub

    'TIME TO NEXT WHOLE MINUTE
    Sub TimeToNextMinute As Long
        
    Dim Ret As Long
            Ret = 
    DateTime.Now + (DateTime.TicksPerMinute * 15'15 = 15 minutes
            Ret = Ret -(Ret Mod DateTime.TicksPerMinute)
        
    Return Ret
    End Sub
     
    Last edited: Dec 23, 2017
    rleiman likes this.
  7. rleiman

    rleiman Well-Known Member Licensed User

    Hi Peter,

    Thanks so much for the code sample. I will use it.

    Very informative. :)
     
  8. Erel

    Erel Administrator Staff Member Licensed User

  9. Peter Simpson

    Peter Simpson Expert Licensed User

    Never heard of this before @Erel, would be a good idea to add this to the commands/functions list (CTRL+Space), or to make it this solution more prominent/easier to find on the forum.

    Cheers...
     
    Last edited: Dec 24, 2017
    MarcoRome likes this.
  10. rleiman

    rleiman Well-Known Member Licensed User

  11. rleiman

    rleiman Well-Known Member Licensed User

    Hi Peter,

    The current time was 09:35 and ran the following code expecting a value of 0 hours, 10 minutes but it returned 9 hours, 50 minutes. Can you let me know what to change in the code to return the 10 minutes if the current time is 09:35?

    Code:
    Dim TimeToNext15Minutes As Long
         TimeToNext15Minutes = TimeToNextMinute
      
        
    ToastMessageShow("The time now is: " & DateTime.GetHour(TimeToNext15Minutes) & _
        
    ":" & DateTime.GetMinute(TimeToNext15Minutes),False)
    Once I can get the remaining time until one of the quarters such as 15 past, 30 past, 45 past and on the hour, I can set up the service to repeat every 15 minutes from that point onwards.
     
  12. Peter Simpson

    Peter Simpson Expert Licensed User

    This is a quick guess so just give it a go (I've not tested this code).
    It will first return the time of the next whole minute, then it should restart the selected service at exactly 15 minute intervals thereafter to the second.

    Code:
    'Call the start service code and set the next time.
    SetExactAndAllowWhileIdle(TimeToNextMinute, <ServiceModuleName>)

    'TIME TO NEXT WHOLE MINUTE
    Sub TimeToNextMinute As Long
        
    Dim Ret As Long
            Ret = 
    DateTime.Now + (DateTime.TicksPerMinute * 15'15 = 15 minutes
            Ret = Ret -(Ret Mod DateTime.TicksPerMinute)  
        
    Return Ret
    End Sub

    'SET EXACTLY
    Sub SetExactAndAllowWhileIdle(Time As Long, ServiceName As String)
        
    Dim Phone As Phone
        
    If Phone.SdkVersion < 23 Then
            StartServiceAtExact(ServiceName, Time, 
    True)
        
    Else
            
    Dim in As Intent
                
    in.Initialize("""")
                
    in.SetComponent(Application.PackageName & "/." &  ServiceName.ToLowerCase)
           
            
    Dim Jin As JavaObject = in
                Jin.RunMethod(
    "setAction"Array(Null))
           
            
    Dim ctxt As JavaObject
                ctxt.InitializeContext
           
            
    Dim Am As JavaObject = ctxt.RunMethod("getSystemService"Array("alarm"))
           
            
    Dim Pi As JavaObject
                Pi = Pi.InitializeStatic(
    "android.app.PendingIntent").RunMethod("getService", _
        
    Array(ctxt, 1in134217728))
            Am.RunMethod(
    "setExactAndAllowWhileIdle"Array(0, Time, Pi))
        
    End If
    End Sub
     
    Last edited: Dec 24, 2017
  13. rleiman

    rleiman Well-Known Member Licensed User

    Hi Peter,

    Thanks for the coding.

    I gave the coding a try at 13:10 and placed a toast in the coding to see if it would return 5 more minutes so the services would restart at 13:15 but it returned 25 minutes instead.

    Maybe the coding needs to be tweaked a bit?

    Code:
    Sub Service_Start (StartingIntent As Intent)
        
    'Call the start service code and set the next time.
        SetExactAndAllowWhileIdle(TimeToNextMinute, "ServiceEmad")

        
    ToastMessageShow("Time for SetExact: " & DateTime.GetHour(TimeToNextMinute) & ":" & _
                             
    DateTime.GetMinute(TimeToNextMinute), True)
    End Sub

    Sub Service_Destroy

    End Sub

    ' Misc. sub routines.
    '--------------------
    'TIME TO NEXT WHOLE MINUTE
    Sub TimeToNextMinute As Long
        
    Dim Ret As Long
        Ret = 
    DateTime.Now + (DateTime.TicksPerMinute * 15'15 = 15 minutes
        Ret = Ret -(Ret Mod DateTime.TicksPerMinute)
        
    Return Ret
    End Sub

    'SET EXACTLY
    Sub SetExactAndAllowWhileIdle(Time As Long, ServiceName As String)
        
    Dim Phone As Phone
        
    If Phone.SdkVersion < 23 Then
            StartServiceAtExact(ServiceName, Time, 
    True)
        
    Else
            
    Dim in As Intent
            
    in.Initialize("""")
            
    in.SetComponent(Application.PackageName & "/." &  ServiceName.ToLowerCase)
        
            
    Dim Jin As JavaObject = in
            Jin.RunMethod(
    "setAction"Array(Null))
        
            
    Dim ctxt As JavaObject
            ctxt.InitializeContext
        
            
    Dim Am As JavaObject = ctxt.RunMethod("getSystemService"Array("alarm"))
        
            
    Dim Pi As JavaObject
            Pi = Pi.InitializeStatic(
    "android.app.PendingIntent").RunMethod("getService", _
        
    Array(ctxt, 1in134217728))
            Am.RunMethod(
    "setExactAndAllowWhileIdle"Array(0, Time, Pi))
        
    End If
    End Sub
     
  14. Peter Simpson

    Peter Simpson Expert Licensed User

    Hello @rleiman, is your test device running Android 6.x, 7.x or 8.x?
     
  15. rleiman

    rleiman Well-Known Member Licensed User

    Yes. It's 7x.
     
  16. Peter Simpson

    Peter Simpson Expert Licensed User

    Hmm okay,
    I looked at the code above and I was convinced that it should be working, I was out at the time. I'm back home now and I copied and pasted the code above with a 5 minute interval into B4A, it stopped working after only 10 minutes (2 x 5 minutes). After looking on the internet I decided to hook up an older device, so I went from a Nexus 6P (8.1.0) to a Nexus 5 (6.0.1), my 7.x device is at another house right now so I can't test it :(. I ran the code again and it worked perfectly well for over 30 minutes on my Nexus 5.

    Please run the code with a one minute interval and print the time out in the logs using Log(DateTime.Time(DateTime.Now)), how long does it run for before stopping. On my 6P it stops after 8 minutes, but I presume that on my 6P it is due to this https://developer.android.com/about/versions/oreo/background.html#overview which JobScheduler might be able to help with, on my 5 it just works flawlessly.
     
  17. rleiman

    rleiman Well-Known Member Licensed User

    Hi Peter,

    Just made the changes and added the log statement. I have not used the logs yet. Can you tell me how to view them?
     
  18. Peter Simpson

    Peter Simpson Expert Licensed User

    Okay, now I know your are joking.
    You've been a member since November 2011, you've posted 604 messages and apparently you have no idea how to use the debug logs. No sorry but I point blank refuse to believe that, that's just not feasible IMO.

    Hmm, not unless you're using a relatives or friends computer and you're learning B4A.
     
    Last edited: Dec 24, 2017
  19. rleiman

    rleiman Well-Known Member Licensed User

    :)

    Yes, it true. I've been using toast messages to debug all along. I never bothered with the logs. You must be laughing like crazy. :p
     
  20. rleiman

    rleiman Well-Known Member Licensed User

    Hi Peter,

    I will look at how to use the notification builder.

    Thanks for all of the help.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice