Switching between network and GPS provider

…衆ロ難τιáo~ 提交于 2019-11-28 08:35:05

Sure, you just get the providers for the network and GPS and pass whichever you want to locationManager.requestLocationUpdates().

When you want to stop listening to a certain provider, call locationManager.removeUpdates() with the listener object you specified in locationManager.requestLocationUpdates().

Network:

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);

You can use LocationManager.isProviderEnabled() doc to see if the appropriate provider is enabled/disabled. There's more info available in the LocationManager docs.

GPS is usually much slower than network since you have to find 3+ far-away satellites, etc.

I am using this

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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!