Android - Getting Network GPS location within a sh

2019-05-26 06:59发布

问题:

I'm trying to set up a quick and dirty GPS lookup via LocationManager which fetches a network location (within 500 meters) every half second for ten seconds. In other words, I'm just trying to find the correct coarse Criteria settings and the correct logic to stop checking after 10 seconds of no better locations within my Handler thread.

I'm thinking my main loop should look something like this:

/**
 * Iteration step time.
 */
private static final int ITERATION_TIMEOUT_STEP = 500; //half-sec intervals
public void run(){
    boolean stop = false;
    counts++;
    if(DEBUG){
        Log.d(TAG, "counts=" + counts);
    }

    //if timeout (10 secs) exceeded, stop tying
    if(counts > 20){ 
        stop = true;
    }

    //location from my listener
    if(bestLocation != null){
       //remove all network and handler callbacks
    } else {
       if(!stop){
          handler.postDelayed(this, ITERATION_TIMEOUT_STEP);
       } else {
          //remove callbacks
       }
    }
}

What I want to know is after I fetch the last known location as my initial best location and kick off my thread, how do I set up the coarse criteria so that I receive a more accurate one than the initial one (in order to compare the two for freshness), which is usually diametrically different from my current location?

回答1:

Well what you are looking for is to ask the device for the best criteria to fetch a coarse location.

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);  // Faster, no GPS fix.
String provider = locationManager.getBestProvider(criteria, true); // only retrieve enabled providers.

Then just register a listener

locationManager.requestLocationUpdates(provider, ITERATION_TIMEOUT_STEP, MIN_LOCATION_UPDATE_DISTANCE, listener); //listener just implements android.location.LocationListener

in the listener you receive an update as such

 void onLocationChanged(Location location) {
     accuracy = location.getAccuracy(); //accuracy of the fix in meters
     timestamp = location.getTime(); //basically what you get from System.currentTimeMillis()
 }

At this point my advice is to sort solely based on accuracy as you can't vary your location that much in 10 seconds yet coarse location updates vary greatly in accuracy.

I hope this helps.