Location and Sensors APIs for official Android documents (TOP)

Source: Internet
Author: User
Tags timedelta
<span id="Label3"></p><p><p>Positioning (location) and sensor (sensors) APIs give full play to the advantages of mobile devices, and you can call these APIs to create highly interactive applications, such as using the Device's own GPS module for positioning, or using network positioning Using the Accelerator module (accelerometer), the acceleration of the monitoring device, the Gyroscope module (gyroscope) monitoring device deflection/tilt rotation angular velocity, The thermometer module (temperature) measuring the temperature of the current device environment, The Barometer module (barometer) measures the air pressure of the current Device's Environment.</p></p><p><p>This article describes the technical essentials of geo-targeting in Android. In the next article, I will describe the knowledge of the sensor, if you want to access the official text of this article, you can click on this link: "location and sensors APIs";</p></p><p><p>You can also refer to these related blog posts:</p></p> <ul> <ul> <li><p>"one Screen Turn deserves another";</p></li> <li><p>"A Deep Dive to location";</p></li> </ul> </ul><p><p>or these training:</p></p> <ul> <ul> <li>"Making Your App Location Aware";</li> </ul> </ul>Positioning Strategy (location Strategies)<p><p>The API for targeting is in the Android.location package. Applications that can be located are not Uncommon. You can use GPS targeting, or network location provider. GPS positioning is more accurate, but more cost-electricity, and more suitable for outdoor, and can not immediately return to the location of the device (although GPS is the most accurate, it only works outdoors, it quickly consumes batte Ry power, and doesn ' t return to the location as quickly as users want), while network station provider uses cellular or WI-FI network positioning, this Confined to the outdoors, and it reacts more sensitively and with less electricity. You can choose which one to choose based on the actual situation (you can also use both targeting methods).</p></p>Difficulty in the implementation of positioning technology (challenges in determining User Location)<p><p>Getting the location of the device is a complex thing (complicated), which explains why locating on a mobile device often produces deviations:</p></p> <ul> <ul> <li><p>Positioning options (multitude of location sources): gps, cell-id, Wi-fi and so on are positioning technologies, in order to decide which way (or in which way) to locate, you need to balance the accuracy, positioning speed, and power-saving Various factors (a matter of trade-offs in accuracy, speed, and battery-efficiency).</p></li> <li><p>Users may be constantly moving (user movement): because the User's location is constantly changing, you must update the User's location regularly (you must. movement by re-estimating user locations every so Often).</p></li> <li><p>The accuracy of positioning is also changing (Varying accuracy): as the results of the positioning may come from different positioning methods, different ways of accuracy are different. The positioning result of a certain positioning method before 10 seconds may be even more accurate than the location of another method at the current moment (a location Obtained. seconds ago from one source might is more accurate than th E Newest location from another).</p></li> </ul> </ul><p><p>The above points lead to occasional inaccuracies in positioning, and the following describes how to overcome these Problems.</p></p>Request Location Update (requesting Locations updates)<p><p>Before we solve the above problem, let's understand how to get the current location on the Android Device.</p></p><p><p>The way to get location information is through callbacks (callback). You can call the <code>requestLocationUpdates()</code> method and pass in the specified parameters (as described below), such as <code>LocationManager</code> the constant values in the class that indicate which method to locate and the <code>LocationListener</code> callback Interface. Where you need to implement the <code>LocationListener</code> methods in the interface, the corresponding method will be called back when the location of the device changes or the positioning method Changes. Examples are shown below:</p></p><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-comment"><span class="hljs-comment">//get A reference to the Locationmanager object</span></span>Locationmanager Locationmanager = (locationmanager)<span class="hljs-keyword"><span class="hljs-keyword"></span> this</span>. Getsystemservice (context.location_service);<span class="hljs-comment"><span class="hljs-comment">//implement the Locationlistener interface and implement the method</span></span>Locationlistener Locationlistener =<span class="hljs-keyword"><span class="hljs-keyword">New</span></span>Locationlistener () {<span class="hljs-comment"><span class="hljs-comment">//when The location of the device changes, the method will be recalled</span></span> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onlocationchanged</span></span>(location Location) {<span class="hljs-comment"><span class="hljs-comment">//using The location parameters of the backhaul to customize the logic</span></span>Makeuseofnewlocation (location); }<span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onstatuschanged</span></span>(String provider,<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>status, Bundle Extras) {}<span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onproviderenabled</span></span>(String Provider) {}<span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">onproviderdisabled</span></span>(String Provider) {} };<span class="hljs-comment"><span class="hljs-comment">//call requestlocationupdates () method Register Location Listener</span></span>Locationmanager.requestlocationupdates (locationmanager.network_provider,<span class="hljs-number"><span class="hljs-number">0</span></span>,<span class="hljs-number"><span class="hljs-number">0</span></span>, locationlistener);</code></pre><p><p>In the requestlocationupdates () method, parameter 1 indicates the positioning method you are using (the above example uses cellular and Wi-fi positioning), and parameter 2 and parameter 3 can control the update frequency of location Information: parameter 2 indicates the minimum time interval to get location information (minimum Time interval between notifications), parameter 3 indicates the minimum moving distance to get the location information (the Third is the minimum change in distance between notifications ), if both parameters are 0, indicates that location information is obtained as frequently as possible (setting both to zero requests locations notifications as frequently as Possible) The parameter 4 is the Locationlistener callback interface for receiving callback information such as the location of the Update.</p></p><p><p>If you need to use GPS for positioning, you can replace the constants in the previous example with <code>LocationManager.NETWORK_PROVIDER</code> <code>LocationManager.GPS_PROVIDER</code> . If you need to use both GPS and Cellular/wi-fi to locate, then you can call <code>requestLocationUpdates()</code> methods two times, one pass at a time, <code>LocationManager.NETWORK_PROVIDER</code> and one pass at a time <code>LocationManager.GPS_PROVIDER</code> .</p></p>Request user Permissions (requesting user Permissions)<p><p>If you use <code>NETWORK_PROVIDER</code> (cellular/wi-fi) location, you need to apply for <code>ACCESS_COARSE_LOCATION</code> permission, such as using <code>GPS_PROVIDER</code> (GPS) location, you need to apply for <code>ACCESS_FINE_LOCATION</code> Permission. Such as:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs r"><span class="hljs-keyword">...</span> > <uses-permission android:name=<span class="hljs-string">"android.permission.ACCESS_FINE_LOCATION"</span> /> <span class="hljs-keyword">...</span></manifest></code></pre></pre>Define an optimal positioning model (defining a models for the best performance)<p><p>To solve some of the problems described above, you need to design a model that achieves relatively precise positioning with good battery life. The design point of this model is: when to use the form of listening to obtain location information, when to use the cached location Information. (when you start and stop listening for updates and if to use cached location Data.)</p></p>Steps for obtaining location information (Flow for obtaining user Locations) <ul> <ul> <li><p>Open the application (Start application);</p></li> <li><p>Turn on location monitoring, Sometimes it can be opened later (sometime later, start listening for updates from desired position Providers.)</p></li> <li><p>Ensure that the location information obtained is up to date, but not necessarily very precise (maintain a "current best estimate" of position by filtering out new, but less accurate fixes.)</p></li> <li><p>Stop Monitoring location information update (stop listening for locations updates)</p></li> <li><p>Use up-to-date location information to estimate custom logic (take advantage of the Estimate)</p></li> </ul> </ul><p><p></p></p><p><p>is a timeline that represents the sequence in which the above steps are performed by time, that is, the process by which the application listens and updates the location information, which is also the location model of the application that typically contains the targeting Functionality.</p></p>Determine when to start listening for update of location information (deciding when to start listening for updates)<p><p>You may want to start listening for real-time changes in the location as soon as the program starts, or only if a feature needs to get location information to start the location Feature. It should be noted that the long-term open positioning function is very power consumption, and in a short period of time to open the positioning function can not guarantee the accuracy of positioning.</p></p><p><p>In general, invoking <code>requestLocationUpdates()</code> a method means that the positioning function is turned on:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm">String locationProvider = LocationManager<span class="hljs-preprocessor">.NETWORK</span>_PROVIDER<span class="hljs-comment">;</span><span class="hljs-keyword">Or</span>, use GPS location data:// String locationProvider = LocationManager<span class="hljs-preprocessor">.GPS</span>_PROVIDER<span class="hljs-comment">;</span>locationManager<span class="hljs-preprocessor">.requestLocationUpdates</span><span class="hljs-number">0</span><span class="hljs-number">0</span>, locationListener)<span class="hljs-comment">;</span></code></pre></pre>Quickly locate with the latest location information (Getting a fast fix with the last Known)<p><p>It is often time consuming to get real-time location information using the listener for the time being (the takes for your locations listener to receive the first site fix is often too long for Users wait), you need to call the method to get the cached location information before the listener returns the exact location information <code>getLastKnownLocation(String)</code> (Until A more accurate position is provided to your locations listener, y OU should utilize a cached location by calling <code>getLastKnownLocation(String)</code> ):</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs avrasm">String locationProvider = LocationManager<span class="hljs-preprocessor">.NETWORK</span>_PROVIDER<span class="hljs-comment">;</span><span class="hljs-keyword">Or</span> use LocationManager<span class="hljs-preprocessor">.GPS</span>_PROVIDERLocation lastKnownLocation = locationManager<span class="hljs-preprocessor">.getLastKnownLocation</span>(locationProvider)<span class="hljs-comment">;</span></code></pre></pre>Determine when the update to stop listening for location information (deciding when to stop listening for updates)<p><p>When listening to location information, you should always consider the situation of good, when the location information should be called, the <code>removeUpdates(PendingIntent)</code> method should stop listening location information:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs dos"><span class="hljs-comment">Remove the listener you previously added</span>locationManager.<span class="hljs-comment">removeUpdates(locationListener);</span></code></pre></pre>Guaranteed to hold the best estimate for the current real-time position (maintaining a Estimate)<p><p>You might think that hearing the latest location information is the most Accurate. But that is not the case-because the way you locate and the environment you are in is Different. You need to switch the mode of positioning according to different scenarios and situations.</p></p><p><p>You can use the following steps to detect if the current location information is accurate:</p></p> <ul> <ul> <li><p>Check that the location information currently obtained is significantly different from the previous position;</p></li> <li><p>Check that the current positioning method is more accurate than the previous positioning method;</p></li> <li><p>Check in the current environment, which method of positioning can be more accurate positioning;</p></li> </ul> </ul><p><p>Examples are as Follows:</p></p><pre class="prettyprint"><code class=" hljs java"><span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Static</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Two_minutes =<span class="hljs-number"><span class="hljs-number"></span> +</span>*<span class="hljs-number"><span class="hljs-number"></span> -</span>*<span class="hljs-number"><span class="hljs-number">2</span></span>;<span class="hljs-javadoc"><span class="hljs-javadoc">/** Determines whether one location reading are better than the current location fix *<span class="hljs-javadoctag"> @param</span> Location The n EW location which you want to evaluate *<span class="hljs-javadoctag"> @param</span> currentbestlocation The current location fix, to which you want To compare the new one * *</span></span><span class="hljs-keyword"><span class="hljs-keyword">protected</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span> <span class="hljs-title"><span class="hljs-title">isbetterlocation</span></span>(location Currentbestlocation) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(currentbestlocation = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//A New location was always better than no</span> location</span> <span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>; }<span class="hljs-comment"><span class="hljs-comment">//Check whether the new location, fix is newer or older</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Timedelta = Location.gettime ()-currentbestlocation.gettime ();<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Issignificantlynewer = timedelta > two_minutes;<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Issignificantlyolder = Timedelta <-two_minutes;<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Isnewer = Timedelta ><span class="hljs-number"><span class="hljs-number">0</span></span>;<span class="hljs-comment"><span class="hljs-comment">//If It's been more than-minutes since the current location with the new</span> location</span> <span class="hljs-comment"><span class="hljs-comment">//because The user has likely moved</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(issignificantlynewer) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>;<span class="hljs-comment"><span class="hljs-comment">//If The new location was more than and minutes older, it must be worse</span></span>}<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(issignificantlyolder) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">false</span></span>; }<span class="hljs-comment"><span class="hljs-comment">//Check whether the new</span> location, fix is more, or less accurate</span> <span class="hljs-keyword"><span class="hljs-keyword">int</span></span>Accuracydelta = (<span class="hljs-keyword"><span class="hljs-keyword">int</span></span>) (location.getaccuracy ()-currentbestlocation.getaccuracy ());<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Islessaccurate = Accuracydelta ><span class="hljs-number"><span class="hljs-number">0</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Ismoreaccurate = Accuracydelta <<span class="hljs-number"><span class="hljs-number">0</span></span>;<span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Issignificantlylessaccurate = Accuracydelta ><span class="hljs-number"><span class="hljs-number"></span> $</span>;<span class="hljs-comment"><span class="hljs-comment">//Check if the old and new</span> location is from the same provider</span> <span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span>Isfromsameprovider = Issameprovider (location.getprovider (), currentbestlocation.getprovider ());<span class="hljs-comment"><span class="hljs-comment">//determine location quality using a combination of timeliness and accuracy</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(ismoreaccurate) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>; }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(isnewer &&!islessaccurate) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>; }<span class="hljs-keyword"><span class="hljs-keyword">Else</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(isnewer &&!issignificantlylessaccurate && Isfromsameprovider) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">true</span></span>; }<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> <span class="hljs-keyword"><span class="hljs-keyword">false</span></span>;}<span class="hljs-javadoc"><span class="hljs-javadoc">/** Checks whether, providers is the same * *</span></span><span class="hljs-keyword"><span class="hljs-keyword">Private</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Boolean</span></span> <span class="hljs-title"><span class="hljs-title">Issameprovider</span></span>(string provider1, String Provider2) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(provider1 = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>Provider2 = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>; }<span class="hljs-keyword"><span class="hljs-keyword">return</span></span>Provider1.equals (provider2);}</code></pre>Trade-offs between power savings and precise positioning (adjusting the model to save battery and data Exchange) <ul> <ul> <li><p>Reduce the life cycle of the listening location (reduce the size of the window): this can reduce the call of the GPS and other modules, that is, to extend the battery, but this may not get accurate location information;</p></li> <li><p>Reduce the callback frequency of the listening method (Set the location providers to return updates less frequently): This also saves power, but at <code>requestLocationUpdates()</code> the cost of positioning accuracy, you can The second and third parameters of the method are set (increasing their values);</p></li> <li><p>Limit the use of multiple positioning methods (Restrict a set of providers): depending on the situation, you can use only one positioning method, which also increases your battery life.</p></li> </ul> </ul> <p><p>Location and Sensors APIs for official Android documents (TOP)</p></p></span>

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.