我在后台运行一项服务,定期从服务器下载数据。我需要每隔一小时下载一次数据。但电池正在快速耗尽。代码如下。如何提高报警功率?
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();
}
}
答案 0 :(得分:1)
仅尝试 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);