Obtaining the Current Location

Source: Internet
Author: User
Tags timedelta

After setting up your application to work with LocationManager, you can begin to obtain location updates.

Set Up the Location Listener
The LocationManager class 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. the 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 already ed. 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. getlongdistance (). 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 the 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 induplicate ate 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 the 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 shocould 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 calling removeUpdates () in onStop (). (onStop () is called when the activity is no longer visible. if you want to learn more about activity lifecycle, read up on the 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 the system notification bar to make the user aware that location data is being used.

 

Related Article

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.