I have a countdown timer that works on a setInterval timer. Despite everything working fine in the Android simulator, the timer stops virtually instantly when the app sleeps on a device.
I tried to replicate this on the simualtor by holding the power button down, but the timer still seems to work. Should the timer pause like this on the device when the phone goes to sleep?
I'm struggling with how to work this out, because the timer displays how many hours/mins/secs are left on a screen, and whenever the user wakes up the phone the timer text is all relative to when the app goes to sleep.
I guess I need to know whether there is anyway to keep this timer working when the app goes to sleep, and being able to update the text of the timer screen - or whether I need to think of another solution.
I've experimented with intents/services, but not having much joy... I guess, perhaps the only thing I can do is clear the text if the app goes to sleep and just schedule a future notificaiton when the timer is due to finish?
Any help or advice on this would be really appreciated - I'm close to pulling my hair out...
3 Answers
I've been using the Android Interval service to work around any issues with timers.
It has been working well in production over the last few months. I just put all of the code needed to calculate duration in the service.js then fire an app event.
Not sure if it will help with your exact scenario but has worked on my projects.
var serviceInterval = 6000; var intent = Ti.Android.createServiceIntent({url:_serviceUrl}); intent.putExtra('interval', serviceInterval); var service = Ti.Android.createService(intent); service.addEventListener('start', function(e) { Ti.API.info('Service Started'); }); service.start();
Chris, you're trying too hard. If your app is asleep, there's no need for it to continue timer processing or update a screen. In the app "pause" event, kill your timer and stop updating the screen. In the app "resume" event, immediately update the screen again, and restart your timer.
Android Timer (even when the phone goes to sleep)
When the phone goes to sleep, the app is “paused” and therefore, the timer is paused. To solve this issue on Android, I added the WAKE_LOCK permission to tiapp.xml:
(…) <android xmlns:android="http://schemas.android.com/apk/res/android"> <manifest android:versionName="1.0.0"> <uses-permission android:name="android.permission.WAKE_LOCK" /> </manifest> <services> <service type="interval" url="myservice.js"/> </services> </android> (…)I am using an interval service that updates a progress bar; for an example, please look at ‘examples/android_services.js’ in the Kitchen Sink.
Iphone Timer
I use the ildeTimerDisabled
Ti.App.idleTimerDisabled = true; // to disable going to sleep (iPhone only) Ti.App.idleTimerDisabled = false; // to re-enable itHope this helps.
Your Answer
Think you can help? Login to answer this question!