使用 AlarmManager 调用自身的服务

Service calling itself with AlarmManager

我有一个应用程序在主 activity 上使用 AlarmManager 调用 Service 并且在 Service 内部发出另一个警报以在片刻之后调用自身。主 activity 中的警报工作正常,但 Service 中的警报未触发。有人知道为什么吗?

这是我主activity中的闹钟:

Intent i = new Intent(this, DailyLogsService.class);

    Calendar time=Calendar.getInstance();
    time.set(Calendar.HOUR_OF_DAY,13);

    time.set(Calendar.MINUTE,15);
    time.set(Calendar.SECOND,0);

    AlarmManager alarmM=(AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pending= PendingIntent.getService(getApplicationContext(),0,i,0);
    //alarmM.cancel(pending);
    alarmM.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pending);
    Toast.makeText(this, "STARTING", Toast.LENGTH_LONG).show();

这是我服务的闹钟

@Override
public void onCreate() {


    Intent i = new Intent(getBaseContext(), DailyLogsService.class);
    Calendar time=Calendar.getInstance();

    time.set(Calendar.HOUR_OF_DAY, 13);
    time.set(Calendar.MINUTE,30);
    time.set(Calendar.SECOND,0);

    AlarmManager alarmM=(AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pending= PendingIntent.getService(getApplicationContext(),0,i,0);
    alarmM.setExact(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pending);


}

onCreate 中的 Service 中的警报代码移至 onStartCommand 方法。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    Intent i = new Intent(getBaseContext(), DailyLogsService.class);
    Calendar time=Calendar.getInstance();
    time.set(Calendar.HOUR_OF_DAY, 13);
    time.set(Calendar.MINUTE,30);
    time.set(Calendar.SECOND,0);

    AlarmManager alarmM=(AlarmManager)getSystemService(ALARM_SERVICE);
    PendingIntent pending= PendingIntent.getService(getApplicationContext(),0,i,0);
    alarmM.setExact(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pending);

    return START_NON_STICKY;
}