警报设置比提供的时间更频繁

Alarm set more frequently than time provided

每当用户进入 MainActivity 时,我都会使用下面的代码将警报设置为 43200000 毫秒的间隔,并删除以前的警报。

int interval =43200000;
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
setContentView(R.layout.activity_main);

Problem is am getting a notification or alarm is fired after every 2 mins i open the app

我建议使用这个: manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pendingIntent); 第二个参数:

triggerAtMillis long: time in milliseconds that the alarm should first go off, using the appropriate clock (depending on the alarm type).

manual

或更好:

am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);

每次启动 broadcastreceiver 和每次启动(启动设备)事件时都会重新触发。

43200000 是 12 小时;)别忘了 此外,为每个毫秒变量使用 long 类型: long interval = 43200000L; 为了防止一些错误。