android - 使用警报管理器重复后台服务
问题描述
目前我正在开发一个使用后台服务的新 android 项目。因为 android 版本 >=Oreo 会自动终止服务。所以我使用AlarmManager。我需要在确切时间显示通知。通知时间在共享首选项中设置。我的警报处理程序正在关注
class AlarmHandler {
private Context context;
AlarmHandler(Context context){
this.context=context;
}
void setAlarmManager(){
Intent intent=new Intent(context,NotificationService.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(alarmManager!=null){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,5000,60000,pendingIntent);
}
}
void cancelAlarmManager(){
Intent intent=new Intent(context,NotificationService.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(context,2,intent,0);
AlarmManager alarmManager= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(alarmManager!=null){
alarmManager.cancel(pendingIntent);
}
}
}
我的通知服务如下
public class NotificationService extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String t1=timeFromsharedPreferences("t1");
String t2=timeFromsharedPreferences("t2");
String systemTime=getCurrentTime();
if(systemTime.equals(t1)){
notify();
}else if(systemTime.equals(t2)){
notify();
}
}
}
我使用以下代码启动 AlarmHandler
AlarmHandler alarmHandler=new AlarmHandler(this);
alarmHandler.cancelAlarmManager();
alarmHandler.setAlarmManager();
我还将广播接收器注册如下
<receiver android:name=".NotificationService" android:enabled="true" />
我的问题是有时它会跳过我的通知。时间安排在晚上 10:00 和早上 7:00。收到晚上 10 点的通知(请注意,我在晚上 10:00 使用电话或在晚上 10:00 前几分钟使用)。但是早上 7:00 的通知一直没有收到。另请注意,我需要每天在同一时间通知。请帮我。
解决方案
你不能有一个重复的精确警报。如果您需要它以精确的间隔重复,您需要在第一个间隔设置一个精确的警报,然后在它触发时重新设置警报,以便为下一个间隔设置,并继续重复该过程。
编辑:
你需要做这样的事情
1.- compute delta in millis to next interval
2.- set exact alarm to fire in delta millis
3.- when the alarm fires, handle the event and then go to step 1
推荐阅读
- spring-boot - Spring 自定义存储库 JpaEntityInformation
- asp.net - ASP.NET Boilerplate Angular 编译错误
- android - Flutter webview 文本选择句柄颜色
- c# - grpc服务器端口共享
- html - 如何使用带有 Bootswatch 主题的字形/图标?
- python - cloudcraper.exceptions.CloudflareChallengeError:检测到 Cloudflare 版本 2 挑战。当我将 cloudcraper 模块与 python 一起使用时出错
- android - 不断收到 java.io.InterruptedIOException: Retrofit2 中的超时
- java - 长期任务的弹性模式
- integration - 如何从 state 中获取列表并在 qore 中对其进行修改?
- .net - 在不需要的地方运行 dotnet 的 Rider 中的 Docker-compose