Switching between gps and network provider [duplic

2019-07-29 09:58发布

This question already has an answer here:

In my app I set both providers with fine and coarse accuracy to listen for location updates. I understand that using fine the location will be provided by the gps, and using coarse the location will be provided by the network provider (from this link http://www.alonsoruibal.com/using-two-locationproviders-on-android/). Now if the gps is disabled I want my app to switch to network, and when gps is enabled to switch back to it. This can be done using onStatusChanged method right? My question is, is this code ok?

public static final int OUT_OF_SERVICE = 0;
public static final int TEMPORARILY_UNAVAILABLE = 1;
public static final int AVAILABLE = 2;

Criteria criteria = new Criteria();
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
providerFine = locationManager.getBestProvider(criteria, true);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
providerCoarse = locationManager.getBestProvider(criteria, true);

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    if (provider.equals(providerFine)) {
        if (status == 0) {
            locationManager.requestLocationUpdates(providerCoarse, 60000,20,this);
        }
        if (status == 2) {
            locationManager.requestLocationUpdates(providerFine, 60000, 20, this);
        }
    }// provider == fine
}

And also, if updates are already requested, (somewhere before in my code, I didn't put that here) (for both providers), would it be ok if I request them again in this onStatusChanged method. Or I have to remove updates first?

1条回答
甜甜的少女心
2楼-- · 2019-07-29 10:25

It looks fine to me. I would recommend removing any update listeners before adding anymore. To keep it clean and consistent.

查看更多
登录 后发表回答