Android API Guides --- Location Strategies

Source: Internet
Author: User
Tags timedelta

Android API Guides --- Location Strategies

Location Strategies

Note: The policy described in this Guide applies to android. location in the platform positioning API. The Google location service API, part of Google Play's service, provides a more powerful, high-level framework that automatically handles Location providers and users' mobile and positioning accuracy. It can also handle scheduling that provides location update based on power consumption parameters. In most cases, you will get better battery performance and more appropriate accuracy, using location service APIs.
For more information about location service APIs, see Google Android location service.
Understand that the application where the user is located is smarter and provides better information to the user. In the development of Android Location Awareness applications, you can use GPS and Android Network Location providers to obtain user locations. Although GPS is the most accurate, it can only be outdoors, it will quickly consume battery power, and the user does not want to return the location as soon as possible. The Android Network Location provider decides to use the mobile phone tower and Wi-Fi signal, providing user location information in the workplace and outdoors, with faster response speed and reduced battery power. To get user location in the application, you can use GPS and network location provider, or just one.
Challenges in determining User Locations
Retrieving user locations from mobile devices can be complicated. Location readings (regardless of their source) can contain errors and inaccuracies for several reasons. Some sources of user positioning errors include:
Multiple sources
GPS, Cell ID, and Wi-Fi provide clues to users' locations respectively. Determine which use and trust are at the balance of accuracy, speed, and battery efficiency.
Mobile users
Due to the change in user location, you must re-estimate the user location and move it at intervals.
Different precision
In the future, the accuracy of location estimation is not the same for each location source. Obtaining a location from one source 10 seconds ago may be more accurate than obtaining the latest location from another or the same source.
These problems make it difficult to obtain reliable user location readings. The information provided in this article helps you deal with these challenges for reliable location readings. It also provides an idea that can be used in applications to provide an accurate and responsive location for user experience.
Request location update
Before solving some of the above positioning errors, we will introduce how to obtain the user's location on Android.
In the get started Android ?? The oid user location works in callback mode. You want to call requestLocationUpdates () to receive location updates from the LocationManager ("Location Manager") and pass a LocationListener. You must implement several callback methods for the LocationListener. When the location manager is called, the user location changes or the service status changes.
For example, the following code demonstrates how to define a LocationListener requirement and location update:

 

// Acquire a reference to the system Location ManagerLocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);// Define a listener that responds to location updatesLocationListener locationListener = new LocationListener() {  public void onLocationChanged(Location location) {   // Called when a new location is 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 updateslocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Use the type of the location provider of the first parameter () in requestLocationUpdates (in this case, the location provider of the mobile phone tower and Wi-Fi ). You can control ?? In the second and third parameters received by the listener, the second update frequency is notification, and the third is the change notification with the minimum distance between the two, at the same time, set the shortest interval between notifications at zero request locations as frequently as possible. The last parameter is your LocationListener, which receives the location update callback.


From the GPS provider, used to replace the GPS_PROVIDER request location update with NETWORK_PROVIDER. You can also request the request from the GPS and call requestLocationUpdates (the network location provides two location updates) twice NETWORK_PROVIDER and one GPS_PROVIDER.


Request User Permissions


In order to receive updates from the NETWORK_PROVIDER or GPS_PROVIDER location, you must separately declare the permission in your android ?? The oid list file requires the user permission. For example:

 

 

   
    ...
 
If you do not have these permissions, your application will fail during runtime when the request location is updated.


Note: If you use both NETWORK_PROVIDER and GPS_PROVIDER, you only need to request the ACCESS_FINE_LOCATION license because it includes two vendors. (Permit ACCESS_COARSE_LOCATION includes permit only for NETWORK_PROVIDER ).


Defined as the best performance model


Location-based applications are now common, but because the user's motion is smaller than the optimal precision, it is complicated to obtain the user's location and save the battery desire. To overcome the need to gain a good user location while maintaining battery power, you must define a consistent model that specifies how the application gets the user location. This model includes the location data when you start and stop listening for updates and when to use the cache.


Traffic acquisition user location


The following is a typical process for obtaining the user location:


Start the application.
After a period of time, start listening for updates from the desired location.
Keep the position by filtering out new ones, but the "current best estimate" is not exactly fixed ".
Stop updating the listening position.
Take advantage of the final best position estimation.
Figure 1 shows that the application in the visualization is listening for location updates. This mode is used to schedule the events that occurred during this time period.

 

Figure 1 shows the time table of the update window where the application listens.


In this mode, a window, during which location update receives many frames, you need your application to add location-based services when making the decision.


Determine when to start listening for updates


When an application is started, or only after a user activates a function, you may need to start listening for location updates immediately. You must know that monitoring and positioning the long coordinate window can consume a lot of battery power, but it may not allow enough precision in the short term.


As shown above, you can start to update the listener by calling requestLocationUpdates:

 

String locationProvider = LocationManager.NETWORK_PROVIDER;// Or, use GPS location data:// String locationProvider = LocationManager.GPS_PROVIDER;locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
Quickly fix the last known location


It takes too long for your location listener to receive the first location. Until a more accurate location is provided to your location listener, you should call getLastKnownLocation (String) to cache the location:

 

 

String locationProvider = LocationManager.NETWORK_PROVIDER;// Or use LocationManager.GPS_PROVIDERLocation lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
Determine when to stop listening for updates


When a new patch is unnecessary, the scope can be very simple. The logic of judgment is very complex depending on your application. When the position is obtained and used, the short gap between the accuracy of estimation is improved. Always watch out, listening for a long time will consume a lot of battery power, so as long as you have what you need, you should stop listening for updated information by calling removeUpdates (PendingIntent:

 

 

// Remove the listener you previously addedlocationManager.removeUpdates(locationListener);
Maintain the current optimal estimate


What you may think of is that the nearest position and position are the most accurate. However, due to changes in the accuracy of positional coordinates, the latest patching is not always the best. You should include logical selection based on several standard position corrections. The standards also depend on the use cases of applications and on-site tests.


Here, you can take several steps to verify the accuracy of the positional coordinates:


Check that the retrieved location is significantly updated compared with previous estimates.
Check that the accuracy claimed by the location is better or worse than previously estimated.
Check the supplier from which the new location is located and determine if you trust it more.
A well-developed example of this logic can look like this:

 

 

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);}
Adjust the mode to save battery and data exchange


When you test your application, you may find that you need to make some adjustments to provide a good geographical location and a good performance model. There are some things that you may change to finding a good balance between the two.


Narrow down the window size


A window with a small update in the location you listen to means that there is less interaction between GPS and the network location service. So, what is the protection ?? Battery life. However, it also allows a small number of locations to select an optimal estimate.


Set location to provide frequent updates with less return


Reducing the rate of new updates during this window can also increase battery efficiency, but at the cost of precision. The value of trade-offs depends on how your applications are used. You can reduce the update rate by changing the specified interval and minimum distance in requestLocationUpdates (the added parameter.


Restrict a group of suppliers


Depending on the level required by your application environment or accuracy, you can choose to use only the network location provider or only GPS, not two. Only interacting with one of the services reduces battery usage at accurate potential costs.


Common application cases


There are also many reasons you may want to get the user location in your application. Here are a couple of scenarios in which you can use the user location to enrich your application. Each solution also introduces a good practice when you should start and stop listening to the location to get a good reading and help prolong battery life.


Tag and location user-created content


You may create an application where user-created content is marked. Think about how users share their local experience, post review restaurants, or record some content, and expand with their current location. How this interaction may occur, as opposed to the service mode at the location, is visualized in Figure 2.

 

Figure 2 shows the user location obtained in the window and listens to the stop window schedule when the user consumes the current location.


This line is obtained with the code in the previous mode where the user is located (figure 1 ). To get the best positioning accuracy, you can choose to start listening for location updates. When the user starts to create content or the application starts, even if, then, the content when listening for updates is ready for publishing or recording. How long does it take to create a typical task of the content and determine the validity of the location estimation allowed for this duration ?? Collection.


Help Users decide where to go


You may create an application that tries to provide users with a set of options for selection. For example, you want to provide nearby restaurants, stores, and entertainment venues, as well as a list of recommended orders based on user location changes.


To adapt to this process, you can choose:


Reordered recommendations when new best estimates are obtained
Stop listening for updates. If the recommended sequence is stable
This model is visualized in figure 3.

Figure 2 shows the user location obtained in the window and listens to the stop window schedule when the user consumes the current location.


This line is obtained with the code in the previous mode where the user is located (figure 1 ). To get the best positioning accuracy, you can choose to start listening for location updates. When the user starts to create content or the application starts, even if, then, the content when listening for updates is ready for publishing or recording. How long does it take to create a typical task of the content and determine the validity of the location estimation allowed for this duration ?? Collection.


Help Users decide where to go


You may create an application that tries to provide users with a set of options for selection. For example, you want to provide nearby restaurants, stores, and entertainment venues, as well as a list of recommended orders based on user location changes.


To adapt to this process, you can choose:


Reordered recommendations when new best estimates are obtained
Stop listening for updates. If the recommended sequence is stable
This model is visualized in figure 3.

 

telnet localhost 
  
Sending location data:
Location is fixed to a set of fixed geographic locations.
This command accepts a longitude and decimal latitude and an optional height of meters. For example:

 

 

geo fix -121.45356 46.51119 4392
Geographic NMEA sends NMEA 0183 sentences.
This command accepts a single NMEA sentence of the type '$ GPGGA' (correction data) or '$ GPRS Mc' (send data. For example:

 

 

geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,130998,011.3,E*62
For more information about how to connect to the simulator console, see use the simulator console.

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.