Thursday, May 31, 2012

Scheduling background task using Alarm Manager Android

All of us know, what Alarm does. Alarms will run in the background, whenever it counter the time, plays nice Music. Alarm wake-up us. Every phone has this feature from low end to high end mobiles.

In Android, we can use Alarms to schedule the tasks. Android has Alarm manager to manage these Alarms.

Service, perform long-running operations in the background and does not provide a user interface.

We need to use Alarm manger as well as service for scheduling background task like downloading information at particular time.

Steps to Create background task :
1. Create project, specify default activity. The following code to set schedule and cancel schedule for background task
public void btnStartSchedule(View v) {

  try {
   AlarmManager alarms = (AlarmManager) this
     .getSystemService(Context.ALARM_SERVICE);

   Intent intent = new Intent(getApplicationContext(),
     AlaramReceiver.class);
   intent.putExtra(AlaramReceiver.ACTION_ALARM,
     AlaramReceiver.ACTION_ALARM);

   final PendingIntent pIntent = PendingIntent.getBroadcast(this,
     1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);

   alarms.setRepeating(AlarmManager.RTC_WAKEUP,
     System.currentTimeMillis(), 10000, pIntent);
   
   toast("Started...");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 public void btnCancelSchedules(View v) {

  Intent intent = new Intent(getApplicationContext(),
    AlaramReceiver.class);
  intent.putExtra(AlaramReceiver.ACTION_ALARM,
    AlaramReceiver.ACTION_ALARM);

  final PendingIntent pIntent = PendingIntent.getBroadcast(this, 1234567,
    intent, PendingIntent.FLAG_UPDATE_CURRENT);

  AlarmManager alarms = (AlarmManager) this
    .getSystemService(Context.ALARM_SERVICE);

  alarms.cancel(pIntent);
  toast("Canceled...");
 }
2. Create AlarmReceiver, for waking up the task
public static String ACTION_ALARM = "com.alarammanager.alaram";

 @Override
 public void onReceive(Context context, Intent intent) {
  
  Log.i("Alarm Receiver", "Entered");
  Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
  
  Bundle bundle = intent.getExtras();
  String action = bundle.getString(ACTION_ALARM);
  if (action.equals(ACTION_ALARM)) {
 Log.i("Alarm Receiver", "If loop");
 Intent inService = new Intent(context,TaskService.class);
 context.startService(inService);
  }
  else
  {
 Log.i("Alarm Receiver", "Else loop");
 Toast.makeText(context, "Else loop", Toast.LENGTH_SHORT).show();
  }
 }
3. Create a Service do background task
public class TaskService extends IntentService {

 public TaskService() {
  super("TaskService");
  // TODO Auto-generated constructor stub
 }

 @Override
 protected void onHandleIntent(Intent arg0) {
  
  // Do some task
Log.i("TaskService","Service running");
 }

}
4. Specify the receiver and service in the Manifest file.

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AlaramScheduleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="AlaramReceiver"
            android:process=":remote" >
        </receiver>

        <service android:name=".TaskService" >
        </service>
    </application>
References : download_source_code

17 comments:

  1. Thanks mr. jeevan, this is all i need

    ReplyDelete
  2. Is the link to the source code broken?

    ReplyDelete
  3. Sorry. Link is broken due to some network maintenance . Restored link, you can download now...
    Thanks for informing.....

    ReplyDelete
  4. code doesn't work for me :( . I am trying to start another app inside service but alarm doesnt starts it. I guess you have set the alarm from start time to 10 sec but nothing happens.. no error even. Below is the code:

    @Override
    protected void onHandleIntent(Intent intent) {
    Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.my.appPkg");
    startActivity(LaunchIntent);
    }

    And my AlarmReceiver :

    public static String ACTION_ALARM = "com.alarmmanager.alarm";

    @Override
    public void onReceive(Context context, Intent intent) {

    Log.i("Alarm Receiver", "Entered");
    Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();

    Bundle bundle = intent.getExtras();
    String action = bundle.getString(ACTION_ALARM);

    if (action.equals(ACTION_ALARM)) {
    Log.i("Alarm Receiver", "If loop");
    Intent inService = new Intent(context, LaunchService.class);
    context.startService(inService);
    } else {
    Log.i("Alarm Receiver", "Else loop");
    Toast.makeText(context, "Else loop", Toast.LENGTH_SHORT).show();
    }
    }

    What should i write in string ALARM_ACTION ?

    ReplyDelete
  5. HI link is broken not able to download code

    ReplyDelete
    Replies
    1. @Kartisk Shah, Link was restored long back. Please try downloading now and let me know if are not able to download. Thanks

      Delete
  6. lets suppose I have to set a repeated alarm after 50 minutes then can I set continuous alarms in a loop?

    ReplyDelete
    Replies
    1. @Rehan, You can set any number of Alarms but you have specify the Unique id to the alarm while creating it.

      Delete
  7. Thanks...it really helped me....

    ReplyDelete
  8. channel '46688c3 com.example.madhavi.alarmintentex/com.example.madhavi.alarmintentex.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

    How to resolve this error?

    ReplyDelete
  9. Hey madhavi, too got the same error, tell me if you found the solution, Thanks

    ReplyDelete
  10. Hi karun,i forgot to register service in androidmanifest....now problem solved.....

    ReplyDelete
  11. Hi karun,i forgot to register service in androidmanifest....now problem solved.....

    ReplyDelete
  12. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. online alarm

    ReplyDelete
  13. Presently I'm certain your venture is great for what it's worth, however that is bad enough. You need all that you put your hands on to be remarkable inside and out. TuneTing.com

    ReplyDelete