Android Alarm Manager and BroadcastReceiver

2019-09-12 11:51发布

问题:

Im trying to set an alarm that will send an intent to a broadcast receiver. The reciever should then print a line in the logcat stating it has worked. However I'm getting no indication that the reciever is receiving anything. I've checked all the things I can think of. Can someone give me some guidance as I am at a loss?

Alarm Method

public void scheduleNextUpdate()
      {

        Intent intent = new Intent(MainActivity.this,AlarmReceiver.class);
        PendingIntent pendingIntent =
            PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


        long currentTimeMillis = System.currentTimeMillis();
        long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS;
        Time nextUpdateTime = new Time();
        nextUpdateTime.set(nextUpdateTimeMillis);

        if (nextUpdateTime.hour < 8 || nextUpdateTime.hour >= 22)
        {
          nextUpdateTime.hour = 8;
          nextUpdateTime.minute = 0;
          nextUpdateTime.second = 0;
          nextUpdateTimeMillis = nextUpdateTime.toMillis(false) + DateUtils.DAY_IN_MILLIS;
        }
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis,nextUpdateTimeMillis,pendingIntent);

        boolean alarmUp = (PendingIntent.getBroadcast(this, 0, 
                new Intent(MainActivity.this,AlarmReceiver.class), 
                PendingIntent.FLAG_NO_CREATE) != null);

        if (alarmUp)
        {
            Log.d("myTag", "Alarm is already active");
        }
}

ReceiverClass

public class AlarmReceiver extends BroadcastReceiver {
    @Override
     public void onReceive(Context context, Intent intent) {  
         System.out.println("Alarm Received");
    intent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
     System.out.println("Alarm Received");
}

The manifest

<receiver android:name=".AlarmReceiver"></receiver>

回答1:

This math seems wrong. I believe you are trying to set an alarm that won't go off for a few generations:

long currentTimeMillis = System.currentTimeMillis();
long nextUpdateTimeMillis = currentTimeMillis * DateUtils.MINUTE_IN_MILLIS;

Maybe you meant for the alarm to go off in one minute:

long nextUpdateTimeMillis = currentTimeMillis + DateUtils.MINUTE_IN_MILLIS;

Anyway first use:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
                          System.currentTimeMillis() + 10000, 
                          5000,
                          pendingIntent);

To confirm your setup is correct, if so you need to recalculate your nextUpdateTimeMillis.