【问题标题】:setRepeating of AlarmManager not respond within the time indicatedAlarmManager 的 setRepeating 在指定的时间内没有响应
【发布时间】:2016-03-09 20:24:46
【问题描述】:

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");
}
}

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

【问题讨论】:

  • 你是如何衡量这个的——在广播接收器中还是在意图服务中?如果在意图服务中,如果有任何事情导致服务长时间运行,它将阻止下一个服务启动。
  • 我在logcat中测量打印时间,打印是从intentservice发送的。
  • 改为从接收器测量,让我们尝试消除潜在的问题来源。如果每分钟都呼叫接收者,则问题出在您的服务上。如果不是,那么它与警报有关。
  • 还要记住“注意:从 API 19 开始,所有重复的警报都是不准确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性准确的警报,每次都重新安排如上所述。旧版targetSdkVersion 早于 API 19 的应用程序将继续将其所有警报(包括重复警报)视为准确。"

标签: android alarmmanager android-intentservice android-broadcastreceiver


【解决方案1】:

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

来自the AlarmManager documentationsetRepeating()

注意:从 API 19 开始,所有重复警报都是不准确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,并如上所述重新安排每次。 targetSdkVersion 早于 API 19 的旧版应用程序将继续将其所有警报(包括重复警报)视为准确。

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

来自setExact() 文档:

注意:只有对准确时间交付有强烈需求的闹钟(例如在请求的时间响起的闹钟)才应按准确时间安排。强烈建议应用程序不要不必要地使用精确警报,因为它们会降低操作系统最大限度地减少电池使用的能力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多