user1002967
user1002967

Reputation: 1

service doing a periodic job

I am developing an Android app which must perform 2 periodic tasks in background:

  1. download files from server every 24 hours.
  2. perform file operations each week on phone sd card.

How do i do this?

Upvotes: 0

Views: 1314

Answers (2)

Kerb
Kerb

Reputation: 1168

Here's what official android docs says about AlarmManager

Note: The Alarm Manager is intended for cases where you want to have 
your application code run at a specific time, even if your application 
is not currently running. For normal timing operations (ticks, timeouts, etc) 
it is easier and much more efficient to use Handler.

Handler documentation.

Upvotes: 0

Khawar
Khawar

Reputation: 5227

Firstly you need to use AlarmManager. When the registered alarm e.g. 24 hours case, will trigger, you can call service from the broadcast receiver of AlarmManager. You need to study a bit about AlarmManager if you don't already know. For further help you can get some idea from code below:

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + 1); //+1 For Next day (24 hours or so...)
cal.set(Calendar.HOUR_OF_DAY,  hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));

AlarmManager am = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.cancel(pendingIntent);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);

Here is how you can set your Alarm. Now when Alarm will be triggered, you will call your service like this:

public class AlarmReceiver extends BroadcastReceiver
{   
   @Override
   public void onReceive(Context arg0, Intent arg1)
   {    
           // Call you service or any task here
   }
}

Last thing, don't forget to mention your broadcast receiver and service in AndroidManifest.xml

<receiver android:name=".AlarmReceiver">
</receiver>    
<service android:name=".MyService"/> 

Upvotes: 3

Related Questions