【发布时间】:2014-12-02 11:39:15
【问题描述】:
我有一项服务,我想每天运行它,因此请检查我的数据库中的一些内容,并在需要时创建通知。 为了每天运行我的服务,我使用了一个alarmManager,它第一次运行良好,但是一旦启动我的服务就会进入无限循环,我知道这是因为alarmManager,因为它只是在什么时候进入循环警报管理器正在启动。这是我的服务代码:
public class MyService extends Service {
...
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
checkMechanicUseer();
this.stopSelf();
return START_NOT_STICKY;
}
private void checkMechanicUseer() {
...
}
@Override
public void onDestroy() {
super.onDestroy();
final SharedPreferences settings = getSharedPreferences("MYSETTINGS",0);
int time = settings.getInt("time",9);
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, 9);
calSet.set(Calendar.MINUTE, 0);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0); // I want it to trigger at 09:00 am each day
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
alarm.setRepeating(
alarm.RTC_WAKEUP,
calSet.getTimeInMillis() ,(1000 * 60 ),
PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
); // I set the (1000 * 60 ) so I can check it with 1 min interval, so I wont need to wait one day for it ... of course I need to change it to (1000 * 60 * 60 * 24)
Toast.makeText(MyService.this, "Service destroyed",Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
我想我需要在某个地方取消闹钟,然后再设置一个。但不知道如何或在哪里做
如果我将alarm.setRepeat 更改为alarm.set 如下所示,问题仍然存在:
alarm.set(
alarm.RTC_WAKEUP,
calSet.getTimeInMillis() + (1000 * 60 ),
PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
);
【问题讨论】:
标签: android alarmmanager infinite-loop