PendingIntent.getService()在警报计划时间之前调用IntentService onHandleIntent

时间:2017-11-20 14:56:16

标签: android android-intent android-notifications android-pendingintent android-intentservice

PendingIntent.getService()在指定的时间之前执行IntentService onHandleIntent()

这是代码。

class MakeAlarm {

public static void scheduleAlarm(Context context) {

    AlarmManager manager = ....;

    boolean enabled = // Some determination logic ;

    //Intent to trigger
    Intent intent = new Intent(context, ReminderService.class);

    PendingIntent operation = PendingIntent
            .getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    if (enabled) {
        //Gather the time preference
        Calendar startTime = // Calendar instance with time set

        //Start at the preferred time
        //If that time has passed today, set for tomorrow
        if (Calendar.getInstance().after(startTime)) {
            startTime.add(Calendar.DATE, 1);
        }

        Log.d(TAG, "Scheduling reminder alarm");
        manager.setInexactRepeating(
                AlarmManager.RTC,
                startTime.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                operation
        );
    } else {
        Log.d(TAG, "Disabling reminder alarm");
        manager.cancel(operation);
    }
  }
}

这是被调用的IntentService:

public class ReminderService extends IntentService {

    private static final String TAG = ReminderService.class.getSimpleName();

    public ReminderService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "reminder event triggered");

        //Present a notification to the user
        NotificationManager manager =
            (NotificationManager) 
getSystemService(Context.NOTIFICATION_SERVICE);

        Notification note = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.notification_title))
                ...
                .build();

        manager.notify(NOTIFICATION_ID, note);
    }
}

警报计划工作正常但我在安排警报时立即收到通知。从日志中可以看出,IntentService onHandleIntent会立即被触发。

1 个答案:

答案 0 :(得分:0)

您需要将时间设置为(今天的日期+ 1)。试试这个。

startTime.set(Calendar.getInstance().get(Calendar.YEAR),
              Calendar.getInstance().get(Calendar.MONTH),
              Calendar.getInstance().get(Calendar.DATE));

startTime.add(Calendar.DATE, 1);