gpt4 book ai didi

java - 为什么当我关闭 Activity 时总是发出火警警报

转载 作者:行者123 更新时间:2023-12-01 21:55:31 25 4
gpt4 key购买 nike

在 Android studio 中,我希望我的应用程序向用户发送通知(如果用户不使用它)。通知 会触发,但总是在我离开 Activity 时以及 8:00 之后

@Override
protected void onStop() {
super.onStop();
System.out.println("STARTED!");
Intent intent = new Intent(this, Alarm.class);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 1);
alarmManager.cancel(pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}

当我离开 Activity 并且时间大于 8:00 时,警报总是会触发一次;

最佳答案

因为它不准确。

文档说“注意:从 API 19 开始,所有重复警报都是不精确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,如上所述重新安排每次时间。targetSdkVersion 早于的旧应用程序API 19 将继续将所有警报(包括重复警报)视为准确的警报。”

https://developer.android.com/training/scheduling/alarms

如果您想要准确的时间,则必须更改您的

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

方法。您应该考虑使用不重复警报(alarmManager.setExact 方法)。如果您仍想安排重复闹钟,可以在“接收闹钟”方法中重新安排。

关于java - 为什么当我关闭 Activity 时总是发出火警警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743489/

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