Android 位置更新最佳实践

监测所选位置提供器的状态,当其不可用时,动态切换到一个新的提供器,当有更适合的提供器可用时,切换到这个更适合的位置提供器

	private void unregisterAllListeners() {
		locationManager.removeUpdates(bestProviderListener);
		locationManager.removeUpdates(bestAvailableProviderListener);
	}
	
	private void registerListener() {
		unregisterAllListeners();
		String bestProvider = locationManager.getBestProvider(criteria, false);
		String bestAvailableProvider = locationManager.getBestProvider(criteria, true);
		
		if(bestProvider == null) {
			Log.d(TAG, "No Location Provider exist on device");
		} else if(bestProvider.equals(bestAvailableProvider)) {
			locationManager.requestLocationUpdates(bestAvailableProvider, minTime, minDistance, bestAvailableProviderListener);
		} else {
			locationManager.requestLocationUpdates(bestProvider, minUpdateTime, minUpdateDistance, bestProviderListener);
		}
		
		if(bestAvailableProvider != null) {
			locationManager.requestLocationUpdates(bestAvailableProvider, minTime, minDistance, bestAvailableProviderListener);
		} else {
			List<String> allProviders = locationManager.getAllProviders();
			for(String provider : allProviders)
				locationManager.requestLocationUpdates(provider, minTime, minDistance, bestProviderListener);
			Log.d(TAG, "No Location Providers currently available.");
		}
	}
	
	private LocationListener bestProviderListener = new LocationListener() {

		@Override
		public void onProviderEnabled(String provider) {
			registerListener();
		}
	}
	
	private LocationListener bestAvailableProviderListener = new LocationListener() {
			
		@Override
		public void onProviderEnabled(String provider) {
			registerListener();
		}
	}

ref: 《Android 4高级编程》 p.474