1

我正在开发一个本机 android 应用程序,每 30 分钟运行一次备份操作。

我正在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 秒内运行重复警报?

4

2 回答 2

1

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

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

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

于 2015-02-07T23:10:33.903 回答
1

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

请在此处查看我的答案:Wake Lock 无法正常用于链接。

于 2015-02-08T17:13:01.857 回答