我想实现一个locationListener,它将根据可用性在网络和GPS提供商之间切换。
例如,如果未启用GPS,我希望它使用网络,但一旦GPS开启,我希望它停止从网络收听位置更新并开始从GPS收听。
同样,我希望它在GPS关闭后立即开始收听网络更新。
这可能吗?
Subquestion
GPS在提供定位时是否与网络一样快?
答案 0 :(得分:9)
当然,您只需获得网络和GPS的提供商,然后将您想要的locationManager.requestLocationUpdates()
传递给他们。
当您想要停止收听某个提供商时,请使用您在locationManager.removeUpdates()
中指定的侦听器对象调用locationManager.requestLocationUpdates()
。
网络:
Criteria crit = new Criteria();
crit.setPowerRequirement(Criteria.POWER_LOW);
crit.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = locationManager.getBestProvider(crit, false);
GPS:
Criteria crit2 = new Criteria();
crit2.setAccuracy(Criteria.ACCURACY_FINE);
provider2 = locationManager.getBestProvider(crit2, false);
您可以使用LocationManager.isProviderEnabled() doc查看是否启用了适当的提供程序。 LocationManager文档中提供了更多信息。
GPS通常比网络慢得多,因为你必须找到3颗以上的远程卫星等。
答案 1 :(得分:1)
我正在使用此
LocationManager locationManager;
LocationListener locationListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager
.getLastKnownLocation(locationProvider);
if (lastKnownLocation == null) {
locationProvider = LocationManager.GPS_PROVIDER;
lastKnownLocation = locationManager
.getLastKnownLocation(locationProvider);
}
if (lastKnownLocation != null) {
makeUseOfNewLocation(lastKnownLocation);
}
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location
// updates
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}