博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Obtaining the Current Location
阅读量:4046 次
发布时间:2019-05-24

本文共 5878 字,大约阅读时间需要 19 分钟。

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

Set Up the Location Listener

The 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 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 notifications at least every 10 seconds and if the device moves by more than 10 meters. The other callback methods notify 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 received.  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.getLongitude()).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 callback, you'll receive location updates from multiple location providers that may have different timestamps and varying levels of accuracy. You'll need to incorporate 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 should consider calling the method which simply queries Android for the last location update previously received by any location providers. Keep in mind that the returned location may be stale. You should 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 and wait for fresh updates from the location provider(s), you should consider displaying an appropriate message before location data is received.

Terminate Location Updates

When you are done with using location data, you should 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 in . ( is called when the activity is no longer visible. If you want to learn more about activity lifecycle, read up on the 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 incorporate 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.

转载地址:http://xxgdi.baihongyu.com/

你可能感兴趣的文章
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
AngularJS2中最基本的文件说明
查看>>
从头开始学习jsp(2)——jsp的基本语法
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>
DIV/CSS:一个贴在左上角的标签
查看>>
Solr及Spring-Data-Solr入门学习
查看>>
Vue组件
查看>>
python_time模块
查看>>
python_configparser(解析ini)
查看>>
selenium学习资料
查看>>
<转>文档视图指针互获
查看>>
从mysql中 导出/导入表及数据
查看>>