Skip to content

Instantly share code, notes, and snippets.

@ayushhgoyal
Last active December 20, 2015 15:29
Show Gist options
  • Select an option

  • Save ayushhgoyal/6154649 to your computer and use it in GitHub Desktop.

Select an option

Save ayushhgoyal/6154649 to your computer and use it in GitHub Desktop.
This is an Alarm Manager Broadcast Receiver, one can schedule a task which will be executed whenever an intent is fired. Task goes in onReceive.
public class ReviveServiceAlarmManagerBroadcastReceiver extends
BroadcastReceiver {
Context temp_context;
final public static String SINGLE_TIME = "onetime";
// static int TIME_INTERVAL_FOR_NETWORK_LOCATIONS = 2;
DatabaseHelper myDatabase;
@Override
public void onReceive(final Context context, Intent intent) {
temp_context = context;
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
// Acquire the lock
if (!wl.isHeld()) {
wl.acquire();
}
// You can do the processing here update the widget/remote views.
wl.release();
}
public void SetAlarm(Context context) {
CustomLog.logBlue(Thread.currentThread().getStackTrace(),
"set network alarm");
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, NetworkTrackingAlarmManagerBR.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(
AlarmManager.RTC_WAKEUP,
(System.currentTimeMillis() + MyVariables.TIME_BEFORE_STARTING_NETWORK_TRACKING),
MyVariables.TIME_INTERVAL_FOR_NETWORK_LOCATIONS, pi);
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, NetworkTrackingAlarmManagerBR.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, NetworkTrackingAlarmManagerBR.class);
intent.putExtra(SINGLE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment