Obtaining the current location

Source: Internet
Author: User
Tags timedelta

After setting up your application to workLocationManager, You can begin to obtain location updates.

Set up the location listener

TheLocationManagerClass exposes a number of methods for applications to receive location updates. In its simplest form, you register an event listener, identify the location manager from which you 'd like to receive location
Updates, and specify the minimum time and distance intervals at which to receive location updates.
onLocationChanged()Callback will be invoked with the frequency that correlates with time and distance intervals.

In the sample code snippet below, the location listener is set up to receive comprehensions at least every 10 seconds and if the device moves by more than 10 meters. the other callback Methods returns y the application any status change coming from the location
Provider.

private final LocationListener listener = new LocationListener() {    @Override    public void onLocationChanged(Location location) {        // A new location update is received.  Do something useful with it.  In this case,        // we're sending the update to a handler which then updates the UI with the new        // location.        Message.obtain(mHandler,                UPDATE_LATLNG,                location.getLatitude() + ", " +                location.getLongitude()).sendToTarget();            ...        }    ...};mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,        10000,          // 10-second interval.        10,             // 10 meters.        listener);
Handle multiple sources of location updates

Generally speaking, a location provider with greater accuracy (GPS) requires a longer fix time than one with lower accuracy (network-based ). if you want to display location data as quickly as possible and update it as more accurate data becomes available,
A common practice is to register a location listener with both GPS and network providers. In
onLocationChanged()Callback, you'll receive location updates from multiple location providers that may have different timestamps and varying levels of accuracy. You'll need to inmarshate logic to disambiguate the location providers
And discard updates that are stale and less accurate. The code snippet below demonstrates a sample implementation of this logic.

private static final int TWO_MINUTES = 1000 * 60 * 2;/** Determines whether one Location reading is better than the current Location fix  * @param location  The new Location that you want to evaluate  * @param currentBestLocation  The current Location fix, to which you want to compare the new one  */protected boolean isBetterLocation(Location location, Location currentBestLocation) {    if (currentBestLocation == null) {        // A new location is always better than no location        return true;    }    // Check whether the new location fix is newer or older    long timeDelta = location.getTime() - currentBestLocation.getTime();    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;    boolean isNewer = timeDelta > 0;    // If it's been more than two minutes since the current location, use the new location    // because the user has likely moved    if (isSignificantlyNewer) {        return true;    // If the new location is more than two minutes older, it must be worse    } else if (isSignificantlyOlder) {        return false;    }    // Check whether the new location fix is more or less accurate    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());    boolean isLessAccurate = accuracyDelta > 0;    boolean isMoreAccurate = accuracyDelta < 0;    boolean isSignificantlyLessAccurate = accuracyDelta > 200;    // Check if the old and new location are from the same provider    boolean isFromSameProvider = isSameProvider(location.getProvider(),            currentBestLocation.getProvider());    // Determine location quality using a combination of timeliness and accuracy    if (isMoreAccurate) {        return true;    } else if (isNewer && !isLessAccurate) {        return true;    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {        return true;    }    return false;}/** Checks whether two providers are the same */private boolean isSameProvider(String provider1, String provider2) {    if (provider1 == null) {      return provider2 == null;    }    return provider1.equals(provider2);}
Use getlastknownlocation () wisely

The setup time for getting a reasonable location fix may not be acceptable for certain applications. You shoshould consider calling
getLastKnownLocation()Method which simply queries Android for the last location update previusly stored ed by any location providers. Keep in mind that the returned location may be stale. You shoshould check the timestamp and Accuracy
Of the returned location and decide whether it is useful for your application. If you elect to discard the location update returned from
getLastKnownLocation()And wait for fresh updates from the location provider (s), You shoshould consider displaying an appropriate message before location data is already ed.

Terminate location updates

When you are done with using location data, you shocould terminate location update to reduce unnecessary consumption of power and network bandwidth. for example, if the user navigates away from an activity where location updates are displayed, you should stop
Location update by callingremoveUpdates()In
onStop()
.(onStop()Is called when the activity is no longer visible. If you want to learn more about activity lifecycle, read up on
Stopping and restarting an activity lesson.

protected void onStop() {    super.onStop();    mLocationManager.removeUpdates(listener);}

Note:For applications that need to continuously receive and process location updates like a near-real time mapping application, it is best to induplicate ate the location update logic in a background service and make use of
System notification bar to make the user aware that location data is being used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.