Android Question Use timers in background service

Stoian

Member
Licensed User
Hello everybody!
I just want play sound in every 5min.
This is my code, but it is not work in sleep mode.

B4X:
Sub Process_Globals
    Dim tmr As Timer
    Dim aud As MediaPlayer
  
End Sub
Sub Service_Start (StartingIntent As Intent)
  
    aud.Initialize()
    aud.Load(File.DirAssets,"audio.wav")
    aud.SetVolume(1,1)
  
  
  
    tmr.Initialize("tmr",5 * 60 * 1000)
    tmr.Enabled=True
End Sub


Sub tmr_Tick
    aud.Play
End Sub

excuse me for my bad english

P.S.
It is not important play sound exactly 5 min. +2min or -2min is not problem.
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
It need just wait 5 min and play sound?
You will need to use a foreground service for this (Service.StartForeground) and acquire a partial lock with PhoneWakeState.

Otherwise the process will be killed.
Use a foregroundservice and use a timer in the service to check something every 5 minutes.
But you should NOT shedule your service to start every x minutes
 
Upvote 0

udg

Expert
Licensed User
Longtime User
You can start foreground, acquire a lock, then start a timer to tick every 5 minutes (never releasing the lock).
The OS will get upset and eventually kill your service.
A second service will start your main service again.
Or, you could count how many times the timer started and on count = 5 (25minutes from first execution) shutdown the service after having set a StartAt 30 minutes from the first run (and so on). This one is based on the hope the OS will not kill your service during those 25mins..

Note that Android is going to me more and more restrictive about background tasks.

Note2: Manfred was quicker by seconds even this time..eheh
 
Upvote 0

Stoian

Member
Licensed User
Guys... I have new problem with timers :D
This code work with WiFi, but doesn't work with mobile network. How I can make it works with all networks?

B4X:
Sub Process_Globals
    Dim note As Notification
    Dim ph As PhoneWakeState
    
    Dim soc As Socket
    
    Dim tmr As Timer
    
    Dim suc, fail As Int
 
End Sub
Sub Service_Start (StartingIntent As Intent)
    note.Initialize
    note.Icon="icon"
    note.SetInfo("title","body",Main)
    note.Notify(1)
    
    Service.StartForeground(1,note)
    
    tmr.Initialize("tmr",60000)
    tmr.Enabled=True
    
    ph.PartialLock
End Sub


Sub tmr_Tick
    soc.Initialize("network")
    soc.Connect("XXX.XXX.XXX.XXX",123,2500)
End Sub


Sub network_Connected (connected As Boolean)
    If(connected=True) Then
        suc=suc+1
    Else
        soc.Close
        fail=fail+1
    End If
End Sub

Sub network_NewData (msg() As Byte)
End Sub


Sub network_Error
    soc.Close
End Sub

Sub network_Terminated
    soc.Close
End Sub
 
Upvote 0
Top