I'm making my own running app for Android and I have a timer that should announce the time every 5 minutes using TextToSpeech. I'm using a Chronometer.OnChronometerTickListener
to track the time and trigger the audio output. It works fine when the phone is plugged into the computer, but when I unplug the phone and lock the screen, the chronometer listener seems to go to sleep after about 30 seconds (so the audio doesn't work). Is there any way to prevent this?

- 7,618
- 2
- 32
- 58
1 Answers
Most of the time, when something needs to be done while the screen is off, it is done in a service
.
Assuming you don't know what a service is, from the docs:
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().
So basically, its just something that runs in the background, including when the screen is off. You may face a problem that your service gets killed by the system, as the android docs specify:
Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.
In this case, you will need to add certain code to keep the service in the foreground and make sure that it doesn't get killed:
startForeground();//keeps service from getting destroyed.
The only problem that this could provide is a constant notification for the time that the service is alive.
You may also use startSticky()
:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Now, say you are done with the timer. You can use:
stopSelf();
to stop the service, or:
Context.stopService();
This notification is not much of a problem though, because the screen is most likely off while the service is running. You can also customize your notification, and it is better for the user to know what is going on in the background.
If you need any more help, feel free to ask.
~Ruchir

- 7,406
- 5
- 48
- 83