gpt4 book ai didi

Android设置alarmManager每天触发

转载 作者:行者123 更新时间:2023-11-30 00:53:36 26 4
gpt4 key购买 nike

在我的应用中,我需要在每天下午 2:00 启动一项服务。现在我写了一次触发警报的代码,每次我打开应用程序都会运行这段代码:

    AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, DownloadReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

alarmMgr.cancel(pIntent);

Calendar cal= Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY,refreshhour);
cal.set(Calendar.MINUTE,refreshmin);
cal.set(Calendar.SECOND, 0);
// if the scheduler date is passed, move scheduler time to tomorrow
if (System.currentTimeMillis() > cal.getTimeInMillis()) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}


if(android.os.Build.VERSION.SDK_INT>=23) {
alarmMgr.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), pIntent);
}
else{
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
}

Q1. 如果设备在 Doze 中,我对 23 以上的 sdk 使用 setAndAllowWhileIdle()模式。我在此功能中找不到任何可以将闹钟设置为每天重复的选项。

Q2. 我也有关于 setInexactRepeating() 的问题,通常是通过设置参数 INTERVAL_DAY 设置每天重复,但是在docs , 它说

As of API 19, all repeating alarms will be inexact and subject to batching with other alarms regardless of their stated repeat interval.

这是否意味着 INTERVAL_DAY 不再起作用,那么我如何才能每天设置闹钟而不重新运行此函数并重置 alarmManager?

最佳答案

尝试下面的代码将解决您的问题-

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

boolean flag = (PendingIntent.getBroadcast(this, 0,
new Intent("totime.action.string"),
PendingIntent.FLAG_NO_CREATE) != null);

if(!flag)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 14);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Intent intent = new Intent("totime.action.string");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) Data_Graph.this.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),(24*60*60*1000), pendingIntent);

}

关于Android设置alarmManager每天触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544693/

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