Positioning strategies for Android

Source: Internet
Author: User
Tags call back timedelta

Original Google
Original address: https://developer.android.com/guide/topics/location/strategies.html
Original copyright: Creative Commons 2.5 Attribution License
Jianan-[email protected]
Version information: This article is based on the 2016-06-17 version of translation
Copyright: CC by-nc-nd 4.0, copy reproduced, but must retain the author's signature and translation links, not deductive and for commercial purposes


Objective

Note: the policy in this article applies to the targeting API in the android.location package on the Android platform. Unlike the Google Location Services Api,google, which is part of Google Play Services, it provides a more powerful and higher-level framework for automating the positioning of data sources, User movement and positioning accuracy issues, you can also adjust the positioning of the method according to the energy consumption parameters you provide. By using the Google location Services API, in most cases you'll get better battery performance while still getting better positioning accuracy. For more information on this part of the Location Services API, please refer to Google geolocation service for Android.

Getting a user's geo-location information can make your application seem smarter, allowing it to distribute more appropriate information to the user. To develop geolocation-related applications for Android, you can use GPS or Android's network location data source to get the user's geographic location. Although GPS positioning is more accurate, it is only suitable for outdoor use, and it also consumes power faster, and it does not return the location information as the user expects. Android's network location data source is the use of cell phone towers and WiFi signals to obtain the user's geographic location information, both indoors and outdoors to provide geographical information in a unified manner, network location response will be faster, the consumption of electricity is also better. Get the user's geographic location in your app, you can use GPS or network targeting at the same time, or you can use only one of them.


Get the challenge of user geolocation information

Getting a user's geo-location information from a mobile device is complicated. There are a number of reasons that can lead to the acquisition of geo-location information (regardless of which data source is used) or errors or inaccurate accuracy. Some user geo-location information gets the data source errors that may result from the following:

    • Multiple location data sources
      GPS, cell phone tower ID, and WiFi, each data source contains a rule for the location of a user. Choosing and trusting which data source data is a tradeoff between positioning accuracy, positioning speed, and power consumption.
    • User Location move
      Because the user's location is constantly changing, you must re-update the user's geo-location information every once in a while to cope with the changing position of the user.
    • Different precision
      Location information accuracy is different for different location data sources. 10 seconds ago Geo-location information obtained from one location data source may be more accurate than the location information just acquired by another or even the same location data source.

These issues make it difficult to get a reliable user location information. This document provides some solutions to help you face these challenges and obtain relatively reliable geolocation information. There are also suggestions to help you provide a precise, responsive, and timely location experience for your users in your application.


Request Location Update

Before addressing some of the positioning errors mentioned above, here's how to get location data on your Android device.

Getting the user's geo-location information on Android is done through callbacks. You pass a locationlistener by calling the Requestlocationupdates () method of the Locationmanager class (location Manager) listeners to indicate to the system that you need to receive geolocation data refresh information. Your Locationlistener must implement some callback methods. These methods change the location information of the user, or the location manager will call back when the Geolocation service status changes.

For example, the following code fragment defines a Locationlistener and requests a location update:

//Get the Locationmanager service of the systemLocationmanager Locationmanager = (Locationmanager) This. Getsystemservice (Context.location_service);//define a Locationlistener to respond to location updatesLocationlistener Locationlistener =NewLocationlistener () { Public void onlocationchanged(Location location) {//Callback when geo-location information changesMakeuseofnewlocation (location); } Public void onstatuschanged(String provider,intStatus, Bundle extras) {} Public void onproviderenabled(String Provider) {} Public void onproviderdisabled(String Provider) {}  };//Register with location manager Locationlistener listen for updatesLocationmanager.requestlocationupdates (Locationmanager.network_provider,0,0, Locationlistener);

The first parameter in the requestlocationupdates () method indicates the type of positional data source used (in this case, the network data source that is located based on the cell phone signal tower and the WiFi signal). You can use the second and third parameters to control how often your listener receives location data information-the second parameter specifies the minimum time interval between two data update notifications, and the third parameter specifies the minimum distance to trigger the next location data update Notification-two parameters are set to 0 to indicate the fastest update possible. The last parameter is your Locationlistener listener, and its callback method will get a callback when there is a location update.

Request to update the location information according to the GPS data source, only need to replace the first parameter Network_provider with Gps_provider. You can also request GPS and network location data sources to update location information, but you need to call the Requestlocationupdates () method two times, one time using Network_provider, one time using Gps_provider.


Requesting permission from a user

In order to be able to receive location update data from the Network_provider or Gps_provider location data source, you must declare access_coarse_location and Access_ separately in the Android manifest file. Fine_location permissions. For example:

<manifest ... >    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    ...</manifest>

Without these permissions, your application will fail to request a location update while it is running.

Note: If you use Network_provider and Gps_provider to locate the data source at the same time, you only need to request Access_fine_location permissions, because it already contains the permissions required by both data sources (Access_coarse_ Location contains only the permissions required to network_provider the data source).


Define the best performance model

Location-based applications are now common, but the acquisition of user-location information is complicated by the poor positioning accuracy, the variety of ways users can move around, access to location information, and the need to reduce power consumption. To solve the contradiction between getting accurate positioning information and saving power consumption, you must identify a unified model to specify how your application obtains the user's positioning information. This model should include when you should start or stop location update monitoring, and when you can use cached location data.

To obtain user location information

Here's a typical process for getting user location information:
1. Launch the application
2. Wait a while to start the listener for target location data source updates
3. Filtering new, but inaccurate positioning information to maintain current geolocation measurement data is optimal.
4. Stop listening for updates to location information
5. Get the best positioning measurement data at the end

Figure 1 below shows an image of an application's events that occur at each stage of the process of monitoring geo-location information updates by a timeline.


Figure 1: A timeline representing the application listening for location refreshes

In the above model, you will receive multiple geo-location information during the update and receive phase of geo-location information, and you need to filter based on the location service you added.

Determine when to initiate geolocation update monitoring

You may want to turn on geo-location update monitoring when the application is started, or you may start listening when the user triggers the relevant function module. But be aware that long-term location monitoring to fix current geo-location information consumes a lot of power, and if the listening time is too short it can lead to inaccurate positioning.
As described in the previous section, you can start the location update listener by calling the Requestlocationupdates () method:

String locationProvider = LocationManager.NETWORK_PROVIDER;// Or, use GPS location data:// String locationProvider = LocationManager.GPS_PROVIDER;00, locationListener);
Get location information for the last quick adjustment fix

The time it takes for your location listener to get the fixed location information for the first time is often long enough for the user to wait. You can call the getlastknownlocation (String) method to get the cached geo-location information until your locator listener obtains more precise geolocation information:

String locationProvider = LocationManager.NETWORK_PROVIDER;// Or use LocationManager.GPS_PROVIDERLocation lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
Determine when to stop location update monitoring

Decide when you no longer need a new status location remediation information depends on your application logic, which can be simple or complex. The more accurate the positioning information is, the shorter the time interval for obtaining geolocation information to use this address location information. Always be aware that the longer you listen for location updates, the more power you consume. So, once you get the location information you need, you should immediately call the removeupdates (pendingintent) method to stop listening for location updates.

// Remove the listener you previously addedlocationManager.removeUpdates(locationListener);
Maintain one of the most accurate positioning information at the moment

You may think that the recently acquired location correction information is the most accurate, however, because of the accuracy of the change in location corrections, the recently obtained correction location information is not necessarily the most accurate. You should add logic based on several criteria in your application to select the fixed value of the positional information. These standards can also vary depending on the user of the application and the actual measured value.

Here are a few steps you can use to verify the accuracy of positional corrections:

    • Check that the positioning correction value is significantly newer than the last measurement.
    • Check whether the accuracy of positioning information is better or worse than the last measured value.
    • Check to see which location data source is providing the new location measurement and whether you trust this location data source.

To synthesize the logic described above, a similar processing code is as follows:

Private Static Final intTwo_minutes = +* -*2;The /** judgment is whether a new positioning measurement is better than the current positioning correction value * @param location needs to be evaluated for new positioning measurements * @param currentbestlocation Current Location corrections Value, which is the location data you want to compare to the new location measurement.protected Boolean isbetterlocation(Location currentbestlocation) {if(Currentbestlocation = =NULL) {//If no correction value is currently positioned, then the new positioning measurement is definitely better        return true; }//Check whether the new location measurements are updated or older data    LongTimedelta = Location.gettime ()-currentbestlocation.gettime ();BooleanIssignificantlynewer = Timedelta > two_minutes;BooleanIssignificantlyolder = Timedelta <-two_minutes;BooleanIsnewer = Timedelta >0;//If the new positioning measurement value is two minutes later than the current positioning correction value, use the new positioning measure, as the user may have moved    if(Issignificantlynewer) {return true;//If the new positioning measure is two minutes older than the current position correction value, the new positioning measurement value should be obsolete}Else if(Issignificantlyolder) {return false; }//Check whether the new positioning measurement accuracy is more accurate    intAccuracydelta = (int) (Location.getaccuracy ()-currentbestlocation.getaccuracy ());BooleanIslessaccurate = Accuracydelta >0;BooleanIsmoreaccurate = Accuracydelta <0;BooleanIssignificantlylessaccurate = Accuracydelta > $;//Check whether the two positioning measurement values originate from the same location data source    BooleanIsfromsameprovider = Issameprovider (Location.getprovider (), Currentbestlocation.getprovider ());//combination positioning timeliness and accuracy to assess the quality of the positioning    if(ismoreaccurate) {return true; }Else if(Isnewer &&!islessaccurate) {return true; }Else if(Isnewer &&!issignificantlylessaccurate && isfromsameprovider) {return true; }return false;}/** Check if two location data sources are the same data source * /Private Boolean Issameprovider(String provider1, String provider2) {if(Provider1 = =NULL) {returnProvider2 = =NULL; }returnProvider1.equals (PROVIDER2);}
Adjust mode to conserve power and data exchange

When you test your application, you may find that the positioning mode you have designed to provide better positioning and better performance may require some tweaking. To get a better balance between the two, here are some things you might need to adjust.

Reduce listening time

Fewer listener-location refresh times mean less interaction with GPS and network location services, and therefore longer battery life. Moreover, this strategy also allows the selection of the best measured values from a small number of positioning information.

Set a lower refresh rate for the location data source

Reducing the frequency of new updates can also increase the efficiency of the battery while listening for location refreshes, but the cost of precision loss needs to be considered. The refresh rate value needs to be weighed against your application's purpose. You can specify the refresh interval and the minimum distance change criteria by adding requestlocationupdates () parameters.

Restricting the use of multiple location data sources

Depending on your application usage scenario and the level of accuracy required, you may need to select either a network location data source or a GPS location data source to be sufficient, without the use of both data sources. In a predictable, acceptable range of accuracy the built-in choice to interact with a location data source can reduce power consumption.


Common Application Cases

There are a number of reasons why you need to get a user's geolocation information. Below is a set of scenarios where you can enrich your application using the user's geo-location information. Each scenario describes when to start or stop listening for location refreshes in order to get good positioning information and save power consumption.

Tagging user-created content with geo-location information

You may want to create an application that uses geolocation information to flag user-created content. For example, a user might want to share the custom of his location, publish a comment on a restaurant, or record something that could be enhanced by their current location information. Figure 2 depicts the interactive model of this process with the location service:


Figure 2: A timeline that contains the user's location acquisition and stops the location listener after consuming the currently acquired geographic location

This timeline is based on the previous model of how to get the user's positioning information in the code (figure I). For better positioning accuracy, you may need to start listening for location information refresh when the user starts creating content or even when the application starts, and then locates the listener after the content is published or saved. You may want to consider how long it takes to create a typical task for a content, and then determine whether the interval is efficient enough to capture a positional measurement.

Help users decide where to go

You might want to create an application that tries to give the user a list of options for where to go. For example, you will be asked to provide a list of nearby restaurants, shops, and apartments, and this list of suggestions will vary depending on the user's geographic location.

To accommodate this process, you can choose to:

    • Refresh the recommendations list when getting updates to locate measurements more accurately
    • Stop listening for location refreshes when the suggested list is relatively stable

Figure 3 describes this model as an image:

Figure 3: A timeline to dynamically update a series of data for each user location refresh


Provide fake location data

When you are developing an application, you will of course need to test whether your access to the user geolocation information model is sufficient to meet the requirements. This kind of testing is easy with an Android device. However, even if you do not have a real machine device, you can also test your location module functionality in the Android emulator using fake location data. Here are three ways to send fake location data to your app: use Android Studio,ddms, or use the "geo" command on the emulator console.

Note: Providing false location information is injected by GPS location information, so you must obtain location refresh data from the GPS location data source in order to fake location information for normal use.

Using Android Studio

Select Tool > Andorid > AVD Manager. Select your AVD in the Android Virtual Machine Manager window and launch the emulator by clicking the Green Play button in the action list.

After that, choose Tool > Android > Android Device Monitor. In the Android Device Monitor window, select the emulator control (emulator controls) tab and Controls enter GPS coordinates as the latitude and longitude coordinates of the user, or use GPX files to specify route planning, or use KML files to identify multiple locations.

Using DDMS

Using the Ddms tool, you can simulate locations in several different ways:

    • Manually send personal latitude coordinates to the device
    • Use a GPX file to describe a route for playback
    • Use a KML file to describe the location of the individual identity used to measure playback

For more information on using DDMS to simulate geolocation, refer to using DDMS.

Using the "Geo" command on the simulator console

To send fake geolocation data from the terminal command line:

  1. Launch your app in the Android emulator while opening the terminal/console in the /tools directory in your SDK.
  2. To connect the emulator's console:

    telnet localhost <console-port>
  3. Send geolocation data:
    • The GEO fix command sends a remediation location.
      This command accepts a pair of decimal latitude and longitude parameters, as well as an optional altitude parameter in meters. For example

      geo fix -121.45356 46.51119 4392
    • Geo NMEA command sends an NMEA 0183 sentence
      This command accepts a single ' GP GG A- (Steadyfixednumberaccording)classtype or person GPRMC ' (transition data) type of sentence. 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 on how to connect to the emulator console, refer to using the simulator console.

Positioning strategies for Android

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.