服务使用AlarmManager调用自身

时间:2015-12-31 06:23:13

标签: android android-service alarmmanager android-pendingintent

我有一个应用程序在主要活动上使用Service调用AlarmManager,并且Service内部会发出另一个警报,以便在此后立即调用自己。主要活动中的警报工作正常,但Service中的警报未启动。谁知道为什么?

这是我主要活动中的警报:

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);


}

1 个答案:

答案 0 :(得分:1)

将警报代码移至onCreateService方法的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;
}