【问题标题】:Inquiry related to AlarmManager and WakeLocksAlarmManager 和 WakeLocks 相关查询
【发布时间】:2015-02-07 22:18:52
【问题描述】:

我正在开发一个每 30 分钟运行一次备份操作的原生 Android 应用。

我为此使用AlarmManager,它工作正常。这是我用来启动警报的代码:

public static void startSync(Context context) {
        alarmIntent = new Intent(context, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
        manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
       // int interval = 3600000;
        int interval =30000 ;
        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

        ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        Toast.makeText(context, "Sync Started", Toast.LENGTH_SHORT).show();
    }

这里是 on receive 方法:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {
        PowerManager pm = (PowerManager) context.getSystemService(context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
        wl.acquire();
        Intent eventService = new Intent(context, SyncInBackground.class);
        context.startService(eventService);
        wl.release();
    }
}

我注意到,当我的设备未处于待机状态时,操作需要 5 秒(我以编程方式计算),但当手机处于待机模式时需要 11 秒。这就是为什么我在后台服务运行备份操作之前使用wake_lock,以使应用程序只需5秒。

但如果手机处于待机模式,我仍然会得到相同的结果......如果不处于待机模式,它仍然需要 11 秒和 5 秒。

如何让我的后台服务在 5 秒而不是 11 秒内运行重复警报?

【问题讨论】:

    标签: android alarmmanager wakelock android-wake-lock repeatingalarm


    【解决方案1】:

    常见的错误:在 OnReceive 中获取唤醒锁什么都不做。 AlarmManager 已经在 OnReceive 中持有唤醒锁。你的方式完全靠运气,当/如果它有效。您必须使用 WakefulBroadcastReceiver 或使用 WakefulIntentService。 WIS 将获取一个静态唤醒锁,该锁将在 OnReceive 返回和服务启动之间处于活动状态。

    在此处查看我的答案:Wake Lock not working properly 获取链接。

    【讨论】:

      【解决方案2】:

      问题是context.startService(eventService) 是一个异步操作,很可能在几毫秒内返回。这意味着,当您在 onReceive 方法中获取 WakeLock 时,只需将其保留几毫秒,然后在服务启动之前释放。

      解决此问题的一种方法是在您的 BroadcastReceiver 和您尝试启动的服务之间共享一个唤醒锁。这就是WakefulIntentService 的工作方式,但您也可以自己执行此操作,例如,通过创建具有两种方法的单例 WakelockManager,一种用于获取唤醒锁,另一种用于释放唤醒锁,然后让 BroadcastReceiver 调用前者,您的服务调用后者。

      另外,请记住,泄漏的唤醒锁(通过获取一个但忘记释放它)可能会对电池使用造成严重后果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-04
        • 1970-01-01
        相关资源
        最近更新 更多