简体   繁体   中英

If Location Manager cannot fetch location with GPS_Provider, switch to NETWORK_Provider

I would like to use GPS_Provider to be my primary method for fetching a Users current location, however, in some cases GPS will not work. If my app can't grab the Users location with GPS, I would like to switch to NETWORK_PROVIDER. How can I implement this?

lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

//setting up criteria (biased toward GPS)
Criteria criteria = new Criteria(); 
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
String providerName = lm.getBestProvider(criteria, true);

//requesting location updates (if app cant use GPS, switch to requestLocationUpdates.NETWORK_PROVIDER)
lm.requestLocationUpdates(providerName, 180000, 0, ll);

One solution is to asynchronously request updates for GPS and NETWORK. You would need two separate listeners for both GPS and NETWORK. Whichever listener returns first you would stop getting updates for the other provider. (ie if you get a result from the network first, stop getting updates for network AND gps.)

Let me know if you are confused or not.

May or may not be a good idea,

What I did, I registered both Network and GPS providers... Once I start fetching the GPS co ordinates, then I will ingore the co ordinates being fetched network provider using location.getProvider() using a boolean variable.

For my implementation. I first check for the gps location, if it comes back null. Then check for the network location.

Location locationGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        if (locationGps != null) {
            //set location as gps
            hasFix = true;
        }

        else if (locationNetwork != null) {
            //set location as network
            hasFix = true;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM