我有一个在后台运行的服务,该服务会定期从服务器下载数据。我每隔一小时需要下载一次数据。但是电池电量消耗很快。代码如下。如何提高警报电源的效率?

public class BackgroundFetchService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int s = super.onStartCommand(intent, flags, startId);

        BackgroundFetchManager.getSharedInstance().setAlarmStatus(false);

        TherapyManager.getSharedInstance().downloadData(new DataManager.DataManagerListener() {
            @Override
            public void onCompletion(AppError error) {
                stopSelf();
            }
        });

        return s;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        //restart this service again in one hour

        if(!BackgroundFetchManager.getSharedInstance().getAlarmStatus()) {
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarm.set(
                    alarm.RTC_WAKEUP,
                    System.currentTimeMillis() + (1000 * 60 * 60),
                    PendingIntent.getService(this, 0, new Intent(this, BackgroundFetchService.class), 0)
            );
            BackgroundFetchManager.getSharedInstance().setAlarmStatus(true);
        }

        super.onDestroy();
    }
}

最佳答案

仅尝试使用RTC,因为根据文档:https://developer.android.com/training/scheduling/alarms.html,RTC在指定的时间激发挂起的意图,但不会唤醒设备。

例如:

AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.set(
        alarm.RTC,
        System.currentTimeMillis() + (1000 * 60 * 60),
        PendingIntent.getService(this, 0, new Intent(this, BackgroundFetchService.class), 0)
);
BackgroundFetchManager.getSharedInstance().setAlarmStatus(true);

10-04 15:01
查看更多