> [hopefully this won't get posted twice. i tried posting it 3 days ago > but have yet to see it on the group, so trying again...] > > Can I rely on Timer and TimerTask to work properly on Android?
That depends on how you use it. Your scenario and TimerTask are not compatible. > I have a background Service with a single Timer, and I schedule > (possibly multiple) TimerTask's via Timer.schedule() > > At the beginning of each implemented TimerTask.run() method, I check > the TimerTask.scheduledExecutionTime() and compare it with the current > time. Sometimes things are fine, and the difference is a small number > of ms. But sometimes things are nowhere near fine, and the invocation > of my TimerTask is *way* late -- like multiple hours late. The device probably went to sleep. > Can an Android phone go into some deep sleep mode when it doesn't > think anything is going on that would cause a TimerTask to be so > late? Absolutely. > Can I not reliably use TimerTask for scheduling events, and > should I be using some Android-specific means (e.g. the AlarmManager, > or a Handler) instead? I would limit TimerTask to activities and short durations. For services, use AlarmManager. As a side benefit, your users will be much happier, because you can get your service out of memory, rather than keeping it around to use a TimerTask: http://www.androidguys.com/2009/12/07/code-pollution-boot-time-services/ > I've searched around a bit, and while I can find numerous posts > suggesting Android-specific timing mechanisms, I have not found > anything that says that java.util.TimerTask shouldn't be sufficient, > the Android docs include no kinds of qualifiers, and this post (from > Mark Murphy, who's written several > good Android books) specifically mentions it as being available: > > http://groups.google.com/group/android-developers/browse_thread/thread/42effa0b2deb1b49/74c79d801be765ad?lnk=gst&q=TimerTask# It is available. It just does not prevent the device from going to sleep and does not wake the device back up. Hence, for some scenarios, TimerTask works just fine. For other scenarios, it doesn't. You'll find the AlarmManager technique covered in _The Busy Coder's Guide to Advanced Android Development_, and demonstrated again in _Android Programming Tutorials_. You'll find a WakefulIntentService, designed to help simplify the pattern, here: http://github.com/commonsguy/cwac-wakeful (BTW, I'm glad you like the books!) -- Mark Murphy (a Commons Guy) http://commonsware.com Android App Developer Books: http://commonsware.com/books.html
-- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en

