一般情况下手机锁屏后,Android系统为了省电以及减少CPU消耗,在一段时间后系统会进入休眠状态,这时CPU会保持在一个相对较低的功耗状态,此时系统会停止定位,从而导致位置不刷新。现在很多应用,需要在手机休眠状态下时刻获取用户位置。那么该怎么做呢?
方法是使用alarmManager定时叫醒cpu进行定位,具体实现如下:
public void init() {
IntentFilter intentFile = new IntentFilter();
intentFile.addAction("repeating");
locationReceiver = new LocationReceiver();
registerReceiver(locationReceiver, intentFile);
Intent intent = new Intent();
intent.setAction("repeating");
pi = PendingIntent.getBroadcast(this, 0, intent, 0);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
}
private void initLocationClient() {
if (mLocationClient == null || mLocationOption == null) {
mLocationClient = new AMapLocationClient(getApplicationContext());
mLocationOption = new AMapLocationClientOption();
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
mLocationOption.setInterval(3000);
mLocationClient.setLocationOption(mLocationOption);
mLocationClient.setLocationListener(this);
}
class LocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
initLocationClient();
mLocationClient.startLocation();
reLosition();
}
public void reLosition() {
am.cancel(pi);
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + 3000, pi);
}
由于小米系统限制了5分钟的唤醒的频率,故需要判断是否为小米系统。修改reLosition()方法
public void reLosition() {
am.cancel(pi);
if (isMiui && calendar != null) {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 3);
am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pi);
} else {
am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3000, pi);
}
}