Android UI How to - Cancel and restart Broadcast








Question

We would like to know how to cancel and restart Broadcast.

Answer

/*from  w w w .jav a  2 s.com*/
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

class AlarmManagerUtil {

  public static void sendUpdateBroadcast(Context ctx) {
    cancelRestartBroadcast(ctx);
    AlarmManager am = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, AlarmManagerUtil.class);
    intent.setAction("repeating");
    long firstTime = SystemClock.elapsedRealtime();
    PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, 0);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5 * 1000,
        sender);
  }

  public static void cancelUpdateBroadcast(Context ctx) {
    restartBroadcast(ctx);
    Intent intent = new Intent(ctx, AlarmManagerUtil.class);
    intent.setAction("repeating");
    PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, 0);
    AlarmManager am = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    am.cancel(sender);
  }

  public static void restartBroadcast(Context ctx) {
    AlarmManager am = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ctx, AlarmManagerUtil.class);
    intent.setAction("restart");
    Calendar calendar = Calendar.getInstance();
    calendar.set(2012, 05, 07, 17, 42, 20);
    long firstTime = SystemClock.elapsedRealtime();
    PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, 0);
    am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
  }

  public static void cancelRestartBroadcast(Context ctx) {
    Intent intent = new Intent(ctx, AlarmManagerUtil.class);
    intent.setAction("restart");
    PendingIntent sender = PendingIntent.getBroadcast(ctx, 0, intent, 0);
    AlarmManager am = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    am.cancel(sender);
  }
}