Thursday, October 7, 2010

Design patterns for scheduling a batch job in an Android Application

In this post, I will discuss design patterns for scheduling periodic jobs in an Android Native Applications. For illustration, i will be referring to sample code from my SMSPost project.


Let's start by discussing how to trigger a job at a predefined time? For many developers, Android Services becomes the default choice. However scheduling jobs through Services is not an optimal solution. Here is why
  • Running a service in the background all the time is a resource drain
  • There is a risk that Android may terminate the service in case of shortage in RAM (Refer to Android process and lifecycle)
Thankfully Android provides APIs to tap into Android system services. The AlarmManager System Service proves handy in this case. For scheduling your job, simply tap into the AlarmManager and schedule a Broadcast Notification event at the desired time. You have flexibility to schedule any date/ time or set fixed intervals for initiating the Broadcast notification. Your application should provision for receiving these asynchronous Broadcasts and perform desired operations.




Sample code for setting a Broadcast using AlarmManager 
try {
     Long firstTime = SystemClock.elapsedRealtime();
     Intent intent  = new Intent(this, AlarmReceiver.class);
     intent.putExtra("alarm_message", "Alarm Scheduled!");
     PendingIntent sender = PendingIntent.getBroadcast(this, Const.url_REQUEST_CODE, intent, 0);

     AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
     am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 60*1000, sender); // set your own frequency
} catch (Exception e) {
     Log.e(Const.TAG, "ERROR IN CODE:"+e.toString());
}


Sample code for Receiving the Broadcast Notification
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
 // TODO Auto-generated method stub
  
 try {
      // your code for scheduled job goes here        
     } catch (Exception e) {
      Log.e(Const.TAG, "ERROR IN CODE:"+e.toString());

     } 
}

Up Next: We would explore design patterns further in specific cases where your scheduled job is expected to execute some heavy resource intensive operations 

No comments: