我有一个应用程序在主要活动上使用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);
}
答案 0 :(得分:1)
将警报代码移至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;
}