Search code examples
androidbroadcastreceiveralarmmanagerandroid-context

Set context for reoccurring alarm in broadcast receiver


In this segment of code I have an issue where I'm not sure what to set the context for setRecurringAlarm(). In this code example I put this but I'm not sure if that's right.

public class AlarmReceiver extends BroadcastReceiver {

private static final int INTERVAL = 15*1000; // check every 15 seconds

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction() != null) {
            if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                Log.v(TAG, "BroadcastReceiver - Received Boot Completed; Set Alarm");

                setRecurringAlarm(this);
            }else{
                Log.v(TAG, "BroadcastReceiver - Received " + intent.getAction());
            }
        }else{
            Log.v(TAG, "BroadcastReceiver - Received AlarmService");
        }
    }

    private void setRecurringAlarm(Context context) {
        Intent receiver = new Intent(context, AlarmReceiver.class);
        PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, receiver, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarms.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL, recurringDownload);
    }
}

Solution

  • You've got your context in onReceive(Context context, Intent intent), use it.