I'm working on an audio app utilizing exoplayer in a foreground service to allow the audio to play with the screen off. This appears to work as intended, but somewhere I read something about adding Wake Locks.
Is that something that would be necessary with a foreground service? The Wake Lock is used to keep the CPU awake, but the foreground service seems to do that while the service is playing.
I decided to test it on the way to work and it played audio with the screen off for +20 minutes without problems. I assume ~20 mins would be long enough for the OS to shut something down without a wake lock.
Yes, Wake lock is used when you start the service again after the device has been rebooted or when the service is killed.
Use it like this:
Create BroadcastReceiver for receiving the broadcast to start a service.
Register that receiver in the Manifest with
ACTION_BOOT_COMPLETEDintent-filter.Now we have created the receiver which will receive a broadcast only one time when the device is rebooted. So we have to use wakelock manager to keep the register our service within a limited time.
Now, create the broadcast receiver which will be used to receive the broadcast to start the service.
Now create a method in LocalReceiver to send the broadcast to start the service.
That's it! We've successfully implemented the wake lock. Now, whenever you want to play a sound. Just send the broadcast to the LocalReceiver & it will get your job done.
Also, don't forget to register this receiver in the Manifest as well as add
android:enabled="true"andandroid:exported="true"where you register your service in Manifest.NOTE : We have used
playMusic()inside theonReceive(). So it will also play the audio when the device is rebooted & the service will be registered. If you just want to bind the service on reboot, then you can simply addstartService()method inside theonReceive()instead of theplayMusic().