androidservicebroadcastreceiveralarmmanagerbootcompleted

AlarmManager inside BroadcastReceiver when BOOT_COMPLETED


I have a Service "GroupsTaskAlarmChecker" that is called every 20 seconds by AlarmManager in onCreate of Groups.class activity this way:

int seconds = 20;

           Intent myIntent = new Intent(Groups.this, GroupsTaskAlarmChecker.class);
           pendingIntent = PendingIntent.getService(Groups.this, 0, myIntent, 0);

           AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

           Calendar calendar = Calendar.getInstance();
           calendar.setTimeInMillis(System.currentTimeMillis());
           calendar.add(Calendar.SECOND, 10);
           alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);

This works perfectly. But I need to do that when device boot. Then I know I have to make AndroidManifest like this:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 <receiver android:name=".ReceiverBoot">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED">
            <category android:name="android.intent.category.HOME">
        </category></action></intent-filter>
    </receiver>

and then mi broadcastReceiver like this:

 public class ReceiverBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    int seconds = 20;

        Intent myIntent = new Intent(context, GroupsTaskAlarmChecker.class);
        pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);

    }
}

but inside this onReceive I dont know how can I do the same that I did before (with intent and alarmManager to start the service each 20 seconds). Error in this line:

 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

Is possible that I can't make an AlarmManager inside BroadcastReceiver?

I thank you all, I am an Android begginer and I need your help. Sorry for my english ;)


Solution

  • ALARM_SERVICE is neither defined in the class ReceiverBoot nor in BroadcastReceiver.

    You should reference Context.ALARM_SERVICE as the argument for getSystemService(String).