The last time this question was asked (by a different user), the answer response was:
If this is in a running activity, you could use Timer/TimerTask and a Handler, or you could use postDelayed() and an AsyncTask.
Here: Android Repetitive Task
I am still learning how to program android. I have gone through the skills I do know including threads and had many issues with my code. Can anyone give an example of how to use: time/timertask and handler OR postDelayed() and AsyncTask.
For Cron like tasks you have to use AlarmManager, this is a system service, for using it in your code you need to call:
AlarmManager myAlarmManager = Context.getSystemService(Context.ALARM_SERVICE).
Full docs about AlarmManager here.
The most suitable approach is through services. I learned how to write services by looking at the source code for the stock Email app that is included with Android.
The general idea is that you override the Service class, and set up alarms to activate your service. Unlike daemons and Windows services, Android services aren't always running - they start up (usually when activated by an alarm), perform work, then shut down. In some cases, you may need to acquire a partial wake lock to keep the service going until it completes the task - otherwise, Android may kill your service prematurely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With