setRepeating of AlarmManager 在指示的时间内没有响应

setRepeating of AlarmManager not respond within the time indicated

AlarmManager 应每 1 分钟重复一次,但每 1、2、3 或 4 分钟重复一次。

由于应用程序我抛出 AlarmManager

public class PacienteApp extends Application {
@Override
public void onCreate() {
    AlarmManager gps = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, GpsReceiver.class);
    PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, 0);
    gps.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 60, pending);
}
}

因为 BroadcastReceiver 调用了 IntentService。

public class GpsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent gps = new Intent(context, GpsIntentService.class);
    context.startService(gps);
}
}

并且intentservice执行任务

public class GpsIntentService extends IntentService {

public GpsIntentService() {
    super("GpsIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    System.out.println("Intent service ejecutado");
}
}

由于这发生在后台,我在前台有几个活动 运行。

自 KitKat (API 19) 起,警报将不精确并一起批处理,以通过最大限度地减少设备需要唤醒的次数来延长电池寿命。

来自 the AlarmManager documentation setRepeating():

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

为了更精确,您需要使用 setExact() 并在每次闹钟唤醒您的应用时重新安排闹钟。不过,请务必小心,因为设置频繁的警报(例如每 1 分钟一次)会大大缩短用户的电池寿命。

来自 setExact() 文档:

Note: only alarms for which there is a strong demand for exact-time delivery (such as an alarm clock ringing at the requested time) should be scheduled as exact. Applications are strongly discouraged from using exact alarms unnecessarily as they reduce the OS's ability to minimize battery use.