gpt4 book ai didi

Android alarmManager 进入循环

转载 作者:行者123 更新时间:2023-11-30 02:31:37 25 4
gpt4 key购买 nike

我有一个服务,我想每天运行它,所以检查我的数据库中的一些东西,如果需要的话创建一​​个通知。为了每天运行我的服务,我使用了一个 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)
);

最佳答案

我认为这是因为您将闹钟设置为过去的日期,首先在 9 点钟触发,然后您将闹钟重置为 9 点钟,但这次是过去的时间,所以闹钟会立即触发,您有一个很好的循环。

检查时间是否不在过去,如果是,则在您的日历中添加一天。

关于Android alarmManager 进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com