这种我刚做过类似的,后台服务自动定时上传位置,锁屏状态连续工作10小时,每分钟上传一次。不用保持唤醒状态和点亮屏幕,非常省电。
主要思路就是用闹钟管理器来保持一个repeat的PendingIntent。
这种办法,不惧怕系统休眠,不需要保持唤醒。
/**
* 检查配置以决定是否开启自动更新
*/
private void _startAutoUpdateAlarm(){
boolean autoUpdate = AppPreference.getAutoUpdate(this);
boolean isIntervalMinValid = AppPreference.isIntervalMinValid(this);
if(autoUpdate&&isIntervalMinValid&&null==_pendingIntent){
Utils.amLog("make repeat");
_pendingIntent = PendingIntent.getService(TraceService.this, 0,
new Intent(TraceService.this, TraceService.class),
Intent.FLAG_ACTIVITY_NEW_TASK);
_alarmManager.cancel(_pendingIntent);
long now = System.currentTimeMillis();
long intervalMillis = 60*1000*AppPreference.getIntervalMin(this);
_alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, intervalMillis, _pendingIntent);
_autoUpdateOn = true;
}else{
Utils.amLog("do not make repeat");
if(null==_pendingIntent){
_pendingIntent = PendingIntent.getService(TraceService.this, 0,
new Intent(TraceService.this, TraceService.class)
, Intent.FLAG_ACTIVITY_NEW_TASK);
}
_alarmManager.cancel(_pendingIntent);
_pendingIntent = null;
_autoUpdateOn = false;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(null==intent){
return super.onStartCommand(intent, flags, startId);
}
Utils.amLog("onStartCommand flags:"+intent.getFlags());
//当服务被后台(Alarm服务)调用时,上传位置
if(Intent.FLAG_FROM_BACKGROUND==intent.getFlags()){
_checkAndUpdateLocation();
}
return START_STICKY;
}
如果你需要进一步的细节的话,留个邮箱窝把这个服务的代码给你