Android 在何处/如何启动AlarmManager,使其在创建Fragement时不会每次执行?
我想设置一个每20秒触发一次的通知。我在片段中的onCreate()方法中设置了AlarmReceiver:Android 在何处/如何启动AlarmManager,使其在创建Fragement时不会每次执行?,android,notifications,alarmmanager,intentservice,Android,Notifications,Alarmmanager,Intentservice,我想设置一个每20秒触发一次的通知。我在片段中的onCreate()方法中设置了AlarmReceiver: Intent alarmIntent = new Intent(getActivity(), IntentService.AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, PendingIntent.FLAG_UPDA
Intent alarmIntent = new Intent(getActivity(), IntentService.AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 20000, pendingIntent);
在我的IntentService类中,我有以下静态类:
public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent send = new Intent(context, IntentService.class);
context.startService(send);
}
}
我想在上面开始的IntentService类中创建通知
AlarmManager工作,每20秒执行一次,但每次创建片段时也会触发它
我的问题是:我应该在何处/如何启动AlarmManager,使其在创建Fragement时不会每次都执行?您不是在告诉alarm manager从现在开始在20秒内启动报警,然后每20秒启动一次,而是从现在开始每隔20秒启动一次。这就是为什么Android会立即触发警报——它会捕捉过去的警报,“现在”是代码完成时的几毫秒过去。您需要确保第一个定时报警是在将来 所以你真正需要的是:
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 20000, 20000, pendingIntent);
这会告诉报警管理器在20秒后安排下一次报警,每20秒重复一次。您并不是告诉报警管理器在20秒内启动报警,从现在开始,然后每20秒启动一次,而是从现在开始,然后每20秒启动一次。这就是为什么Android会立即触发警报——它会捕捉过去的警报,“现在”是代码完成时的几毫秒过去。您需要确保第一个定时报警是在将来 所以你真正需要的是:
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 20000, 20000, pendingIntent);
这会告诉报警管理器在20秒内安排下一个报警,每20秒重复一次。在启动alaram之前使用此选项:if(PendingEvent=null){START alaram manager}在启动alaram之前使用此选项:if(pendingIntent=null){START alaram MANAGER}很高兴我能帮忙-最近才遇到同样的问题:-)很高兴我能帮忙-最近才遇到同样的问题:-)