Knowing the location of the user can make your program smarter and provide better information to your users, and when developing a location-aware program, you can use GPS or Android's network location provider to get the user's location. Although the use of GPS is the most accurate, but he can only work outdoors, and he is more power consumption, not in time to return the user's location information. By comparison, Android's network location provider uses a base station or Wi-Fi signal to determine the user's location, which can work outdoors, work indoors, react quickly and consume less power. You can use either of these two ways to get location information, or you can use one of these two ways.
Obtaining location information through a user's mobile device is complex, and there are a number of reasons why an error occurred while getting the location.
The reasons are as follows: There are many ways to get the location, through Gps,cell-id, Wi-Fi, and so on, these three ways can let you get location information, determine which way to use the information will be involved in precision, response speed and power consumption and so on. Users are constantly moving, then you have to keep estimating the location information of the users. The location information obtained from a position source is not immutable, and 10 seconds ago you get the location information from a position source that is more accurate than the latest location information you get from a or B.
1. Request Location Update
Before we locate some of the above questions, let's take a look at how to get location information on Android.
To get user location information via a callback on Android, through the Locationmanager requestlocationupdates (), you can register the current activity to Locationmanager, This locationmanager can periodically inform this registered activity of the latest location information, the activity must provide listeners to let Locationmanager swap, The listener that is provided must implement the following methods of Locationlistener, which will be Locationmanager callback when the user's position or the status of the service in the network location changes.
Acquire a reference to the system Location Manager
Locationmanager Locationmanager = (locationmanager) this.getsystemservice (Context.location_service);
Define a listener that responds to location updates
Locationlistener Locationlistener = new Locationlistener () {
public void onlocationchanged (Location Location) {
Called when a new location was found by the network location provider.
Makeuseofnewlocation (location);
}
public void onstatuschanged (String provider, int status, Bundle extras) {}
public void onproviderenabled (String provider) {}
public void onproviderdisabled (String provider) {}
};
Register the listener with the Location Manager to receive Location updates
Locationmanager.requestlocationupdates (locationmanager.network_provider, 0, 0, Locationlistener);
Extension: Let's take a look at the relevant APIs used in the above code
Locationmanager: This class allows you to use the system's location services, which allow the Android program to periodically get updates to the physical location of the device, or when the user approaches a particular physical location, the application can send a special intent to alert the user. You cannot instantiate this class to get the instance object of the class, but rather to get the handle by Context.getsystemservice (Context.location_service)
public void Requestlocationupdates (String provider, long mintime, float mindistance, Locationlistener listener)
Registers the current activity to be notified periodically by the specified provider. If the current position or the state of the specified provider changes, the Locationlistener provided by the current activity is periodically invoked. Getting the latest location information takes some time, and the application can get a closest location through the Getlastknownlocation (String) method (the place is still to be weighed).
If the current provider service is closed by the user, the registration update is stopped, and the provider status becomes disable,onproviderdisabled (String) method is invoked. Once the current provider is opened again, the onproviderenabled will be invoked and the registration update will start again.
The second and third parameters enable you to control the frequency of location updates. The first parameter mintime represents the interval between two update locations, and if the mintime is greater than 0, then Locationmanager will rest mintime time after an update, and then continue the update, which will save electricity. The third parameter mindistance is the condition of a location update, because the user's location may be constantly changing, the current two times the distance is greater than mindistance, will update. If you want to get updates as soon as possible, set both parameters to 0.
When keeping the GPS or wireless network service running, the service in the background should be set to a sufficient time interval so that the device does not consume too much power and the time interval less than 60000 milliseconds is not recommended.
The thread that calls the location service must be a thread that contains looper.
Location Android.location.LocationManager.getLastKnownLocation (String provider)
To get the last position correction from the specified provider, this method can also be used without opening the provider, but this time the provider state is disable and the return value of the function is null. Note that this return value is location possible for state-owned enterprises, such as shutting down mobile devices or moving to other locations.
Problem:
1. How the system caches location correction information.
The Getlastknownlocation method gets the last cached location information, and when the Requestlocationupdates method is invoked, the location service starts to constantly cache updated location corrections. When the Removeupdates method is invoked to stop the update, the cache stops, and this time the Getlastknownlocation method is invoked to obtain the last cached location correction information. Because the cached location information is likely to expire, you need to determine if the return value is null and special handling.
2. How to open the position service on the mobile phone.
Take my G3 for example, open the "set"-----"Location", you will see the following interface
First Correspondence Network_provider
Second Correspondence Gps_provider
If you do not open the service here, your program is unable to obtain location information.
2. Permission settings for location service
In order to use Network_provider or Gps_provider to obtain location information, you must configure the user's permissions in the program, get the user's location information to require permissions access_coarse_location or Access_fine_ LOCATION
<manifest ... >
<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
Note: If you use Network_provider and Gps_provider in two ways, you only need to declare access_fine_location this permission, which includes the permissions required for both of these PROVIDER. Access_coarse_location permission only declares the permissions required by the Network_provider
3. Define a best model for obtaining User configuration information
A basic access to get location information is simple, but if you want to take into account the accuracy of location information, the user's mobile, get the location of the method, for mobile phone power demand, get location is very complex.
You have to build a model to guide how your program gets the user's location, which shows when to listen and remove a listening location update, and when to cache location information data
Steps to get user location information open the program to start the listening location update to determine the best current location information stop listening using the best location information
4. Specific steps to achieve
4.1 Determine when to start listening for updates
You may start a listening location update immediately after the program is started, or listen after a user's action. What you need to know is that the correction of the long listening position information quickly consumes a lot of power, but in a short time it doesn't get enough accurate information.
Locationprovider locationprovider = Locationmanager.network_provider;
Or, use GPS location data:
Locationprovider locationprovider = Locationmanager.gps_provider;
Locationmanager.requestlocationupdates (locationprovider, 0, 0, Locationlistener);
4.2 Use the previous known location to get a quick position correction
Locationlistener it will take a long time to get the first position fixed, and in order to avoid the user waiting, you should use Getlastknownlocation (String) before your locationlistener gets to a more precise position. Gets the location of a cache.
Locationprovider locationprovider = Locationmanager.network_provider;
Or Use Locationmanager.gps_provider
Location lastknownlocation = locationmanager.getlastknownlocation (Locationprovider);
4.3 Determine when to stop the listening location update
Determining when those new location fixes are not needed logically is simple or complex depending on your application. The shorter the interval between the time that the position information is obtained and the time that the position information is used, the higher the accuracy of the position prediction. Always be aware that a long listening position update consumes a lot of power. Once you have the information you need, you should immediately call the Removeupdates (Pendingintent) method to stop listening.
Remove the listener you previously added
locationmanager.removeupdates (locationlistener);
Note: This method must be invoked, and if you do not call this method immediately you exit the program and it will still be updated.
4.4 Determine one of the most accurate current position information
You may think the latest position correction is the most accurate, but because of the various accuracy of position correction, the latest position correction is not necessarily the best. You should introduce a logic to choose the best position correction according to some conditions. These conditions depend on your program.
Here are some steps you can use to verify the location correction
Verify that the location you are getting is significantly higher than the previous
Verify that the precision of this position is higher or lower than the previous position
Verify the location that provider provided and determine if the provider is trustworthy.
Here is an example of a detailed judgment:
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's you want to evaluate * @param currentbestlocation of the current Location fix, to which your want to compare the new O NE */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.gett IME (); 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 Moved if (issignificantlynewer) {return true; If The new location is more than two minutes older, it must to be worse} else if (Issignificantlyolder) {RET Urn false; }
Check whether the new location fix is more or less accurate int accuracydelta = (int) (location.getaccuracy ()-cur Rentbestlocation.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.g Etprovider (), 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); }
Turn from: http://www.cnblogs.com/transmuse/archive/2010/12/31/1923358.html