Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android regular task (cronjob equivalent)

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.

like image 784
Dech Avatar asked Mar 10 '11 22:03

Dech


2 Answers

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.

like image 138
Lucas S. Avatar answered Oct 14 '22 23:10

Lucas S.


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.

like image 30
Melllvar Avatar answered Oct 14 '22 21:10

Melllvar