这是一个与LocationManager相关的效率问题(更常见的是管理Android中的内存与CPU使用率)。假设我有一个长期运行的服务,它希望每隔60秒使用一次LocationManager的getLastKnownLocation方法来更新位置。此服务使用TimerTask和具有重复固定延迟执行的Time。最好是创建一个实例字段mLocationManager并在服务的生命周期中保留它,或者最好在每次执行TimerTask时实例化LocationManager,假设VM只会在需要时保留它?在代码中:
public class ProximityService extends Service {
private LocationManager mLocationManager;
@Override
public void onCreate() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Timer timer = new Timer();
TimerTask mGetLastKnownLocationTask = new GetLastKnownLocationTask();
timer.schedule(mGetLastKnownLocationTask, 0, 60000);
}
private class GetLastKnownLocationTask extends TimerTask {
public void run() {
Location mLocation =
mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Do something with mLocation
}
}
...
}
VS。
...
@Override
public void onCreate() {
Timer timer = new Timer();
TimerTask mGetLastKnownLocationTask = new GetLastKnownLocationTask();
timer.schedule(mGetLastKnownLocationTask, 0, 60000);
}
private class GetLastKnownLocationTask extends TimerTask {
public void run() {
LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location mLocation =
mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Do something with mLocation
}
}
注意:我不需要LocationListener来保持GPS活动。这是在应用程序的另一部分中使用单独的服务处理的。在这里,我只想以固定的间隔检查最近的已知位置。
答案 0 :(得分:0)
获取位置管理器一次,然后注册被动位置监听器不是更好吗?必须调用getLastKnownLocation()应该是一个快速的解决方案,当你没有时间获得有效的位置修复时,不一定要重复使用。
...一样
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//change best provider to a passive location service.
String bestProvider = lm.getBestProvider(new Criteria(), true);
if(bestProvider!=null){
lm.requestLocationUpdates(bestProvider, 1000 * 60 * 15 ,5000,
new LocationListener {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
);
}