在Android中获取用户位置的好方法


211

问题:

尽快使用户的当前位置在阈值之内,同时节省电池。

为什么问题是一个问题:

首先,android有两个提供程序;网络和GPS。有时网络会更好,有时GPS会更好。

“更好”是指速度与精度之比。
如果我几乎可以立即获得位置信息而无需打开GPS,则我愿意牺牲几米的精度。

其次,如果您请求位置更改的更新,并且当前位置稳定,则不会发送任何内容。

Google提供了一个确定“最佳”位置的示例:http : //developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate
但我认为这没有应该做的那么好/可能。

我有点困惑,为什么google没有用于位置的标准化API,开发人员不必关心位置的来源,您只需指定所需的内容,然后电话为您选择。

我需要什么帮助:

我需要找到一种确定“最佳”位置的好方法,也许是通过某种启发式方法,或者通过一些第三方库。

这并不意味着确定最佳提供商!
我可能会使用所有提供商,并从中选择最好的提供商。

应用程序的背景:

该应用程序将以固定的时间间隔(假设每10分钟左右)收集用户的位置,并将其发送到服务器。
该应用程序应尽可能节省电池,并且该位置的精度应为X(50-100?)米。

目标是以后能够在一天中在地图上绘制用户的路径,因此我需要足够的准确性。

其他:

您认为期望和接受的精度的合理值是多少?
我一直在使用100m作为可接受的值,并根据需要使用30m,这是个要问的问题吗?
我希望以后能够在地图上绘制用户的路径。
理想的100m和可接受的500m是否更好?

另外,现在我在每次位置更新中最多打开GPS 60秒,如果您在室内,精度可能达到200m,这太短了,无法找到位置吗?


这是我当前的代码,感谢任何反馈(除了缺少错误检查(TODO)):

protected void runTask() {
    final LocationManager locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    updateBestLocation(locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    updateBestLocation(locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (getLocationQuality(bestLocation) != LocationQuality.GOOD) {
        Looper.prepare();
        setLooper(Looper.myLooper());
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (getLocationQuality(bestLocation) != LocationQuality.GOOD)
                    return;
                // We're done
                Looper l = getLooper();
                if (l != null) l.quit();
            }

            public void onProviderEnabled(String provider) {}

            public void onProviderDisabled(String provider) {}

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                // TODO Auto-generated method stub
                Log.i("LocationCollector", "Fail");
                Looper l = getLooper();
                if (l != null) l.quit();
            }
        };
        // Register the listener with the Location Manager to receive
        // location updates
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 1000, 1, locationListener,
                Looper.myLooper());
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, 1000, 1,
                locationListener, Looper.myLooper());
        Timer t = new Timer();
        t.schedule(new TimerTask() {

            @Override
            public void run() {
                Looper l = getLooper();
                if (l != null) l.quit();
                // Log.i("LocationCollector",
                // "Stopping collector due to timeout");
            }
        }, MAX_POLLING_TIME);
        Looper.loop();
        t.cancel();
        locationManager.removeUpdates(locationListener);
        setLooper(null);
    }
    if (getLocationQuality(bestLocation) != LocationQuality.BAD) 
        sendUpdate(locationToString(bestLocation));
    else Log.w("LocationCollector", "Failed to get a location");
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < MAX_AGE
            && location.getAccuracy() <= GOOD_ACCURACY)
        return LocationQuality.GOOD;
    if (location.getAccuracy() <= ACCEPTED_ACCURACY)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

// Pretty much an unmodified version of googles example
protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // 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 location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // 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 location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

7
鸣叫确实很晚,但是最近在IO 2013上宣布的“融合位置提供者”似乎可以满足您的许多需求-developer.android.com/google/play-services/location.html
Matt

getBestLocation()的最后一行不应该是:return currentBestLocation; 而不是返回bestLocation ;?
加夫里尔2015年

Answers:


164

看起来我们正在编码相同的应用程序;-)
这是我当前的实现。我仍处于GPS上传器应用程序的Beta测试阶段,因此可能会有很多改进。但到目前为止,它似乎运行良好。

/**
 * try to get the 'best' location selected from all providers
 */
private Location getBestLocation() {
    Location gpslocation = getLocationByProvider(LocationManager.GPS_PROVIDER);
    Location networkLocation =
            getLocationByProvider(LocationManager.NETWORK_PROVIDER);
    // if we have only one location available, the choice is easy
    if (gpslocation == null) {
        Log.d(TAG, "No GPS Location available.");
        return networkLocation;
    }
    if (networkLocation == null) {
        Log.d(TAG, "No Network Location available");
        return gpslocation;
    }
    // a locationupdate is considered 'old' if its older than the configured
    // update interval. this means, we didn't get a
    // update from this provider since the last check
    long old = System.currentTimeMillis() - getGPSCheckMilliSecsFromPrefs();
    boolean gpsIsOld = (gpslocation.getTime() < old);
    boolean networkIsOld = (networkLocation.getTime() < old);
    // gps is current and available, gps is better than network
    if (!gpsIsOld) {
        Log.d(TAG, "Returning current GPS Location");
        return gpslocation;
    }
    // gps is old, we can't trust it. use network location
    if (!networkIsOld) {
        Log.d(TAG, "GPS is old, Network is current, returning network");
        return networkLocation;
    }
    // both are old return the newer of those two
    if (gpslocation.getTime() > networkLocation.getTime()) {
        Log.d(TAG, "Both are old, returning gps(newer)");
        return gpslocation;
    } else {
        Log.d(TAG, "Both are old, returning network(newer)");
        return networkLocation;
    }
}

/**
 * get the last known location from a specific provider (network/gps)
 */
private Location getLocationByProvider(String provider) {
    Location location = null;
    if (!isProviderSupported(provider)) {
        return null;
    }
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Cannot acces Provider " + provider);
    }
    return location;
}

编辑:这是请求位置提供者定期更新的部分:

public void startRecording() {
    gpsTimer.cancel();
    gpsTimer = new Timer();
    long checkInterval = getGPSCheckMilliSecsFromPrefs();
    long minDistance = getMinDistanceFromPrefs();
    // receive updates
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    for (String s : locationManager.getAllProviders()) {
        locationManager.requestLocationUpdates(s, checkInterval,
                minDistance, new LocationListener() {

                    @Override
                    public void onStatusChanged(String provider,
                            int status, Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}

                    @Override
                    public void onLocationChanged(Location location) {
                        // if this is a gps location, we can use it
                        if (location.getProvider().equals(
                                LocationManager.GPS_PROVIDER)) {
                            doLocationUpdate(location, true);
                        }
                    }
                });
        // //Toast.makeText(this, "GPS Service STARTED",
        // Toast.LENGTH_LONG).show();
        gps_recorder_running = true;
    }
    // start the gps receiver thread
    gpsTimer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Location location = getBestLocation();
            doLocationUpdate(location, false);
        }
    }, 0, checkInterval);
}

public void doLocationUpdate(Location l, boolean force) {
    long minDistance = getMinDistanceFromPrefs();
    Log.d(TAG, "update received:" + l);
    if (l == null) {
        Log.d(TAG, "Empty location");
        if (force)
            Toast.makeText(this, "Current location not available",
                    Toast.LENGTH_SHORT).show();
        return;
    }
    if (lastLocation != null) {
        float distance = l.distanceTo(lastLocation);
        Log.d(TAG, "Distance to last: " + distance);
        if (l.distanceTo(lastLocation) < minDistance && !force) {
            Log.d(TAG, "Position didn't change");
            return;
        }
        if (l.getAccuracy() >= lastLocation.getAccuracy()
                && l.distanceTo(lastLocation) < l.getAccuracy() && !force) {
            Log.d(TAG,
                    "Accuracy got worse and we are still "
                      + "within the accuracy range.. Not updating");
            return;
        }
        if (l.getTime() <= lastprovidertimestamp && !force) {
            Log.d(TAG, "Timestamp not never than last");
            return;
        }
    }
    // upload/store your location here
}

注意事项:

  • 请勿过于频繁地请求GPS更新,因为它会消耗电池电量。我目前使用30分钟作为我的应用程序的默认设置。

  • 添加“到最近的已知位置的最小距离”检查。如果没有此功能,当GPS不可用且位置已从手机信号塔进行三角测量时,您的点将“跳来跳去”。或者您可以检查新位置是否在最后一个已知位置的精度值之外。


2
您实际上从未获得过一个新的位置,只使用了以前更新中的位置。我认为,通过添加不时打开GPS来更新位置的侦听器,此代码将大大受益。
Nicklas A.

2
抱歉,我以为您只对从所有可用位置中选择最好的部分感兴趣。我在上面添加了要求这些代码的代码。如果收到新的GPS位置,则会立即存储/上传。如果收到网络位置更新,则会将其存储以供参考,并“希望”我也将收到gps更新,直到进行下一次位置检查为止。
Gryphius 2011年

2
我也有一个stopRecording()方法取消了计时器。我最终从计时器切换到ScheduledThreadPoolExecutor,所以stopRecording现在基本上调用了executor.shutdown()并注销了所有位置更新侦听器
Gryphius 2013年

1
根据我的scm,stopRecording仅调用gpsTimer.cancel()并设置gps_recorder_running = false,因此就像您的情况一样,那时不清理监听器。当前代码在矢量中跟踪所有活动的侦听器,而1.5年前写此答案时我没有这个。
Gryphius

1
它已经在github上了,但是我不确定这仍然是当今做GPS东西的最好方法。自从我编写这段代码以来,Afaik他们已经对位置API进行了许多改进。
Gryphius 2014年

33

要为您的应用选择合适的位置提供者,可以使用Criteria对象:

Criteria myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_HIGH);
myCriteria.setPowerRequirement(Criteria.POWER_LOW);
// let Android select the right location provider for you
String myProvider = locationManager.getBestProvider(myCriteria, true); 

// finally require updates at -at least- the desired rate
long minTimeMillis = 600000; // 600,000 milliseconds make 10 minutes
locationManager.requestLocationUpdates(myProvider,minTimeMillis,0,locationListener); 

请阅读requestLocationUpdates文档,以获取有关如何考虑参数的更多详细信息:

可以使用minTime和minDistance参数控制通知的频率。如果minTime大于0,则LocationManager可能会在两次位置更新之间休息minTime毫秒,以节省电量。如果minDistance大于0,则仅当设备移动minDistance米时,才会广播位置。要尽可能频繁地获取通知,请将两个参数都设置为0。

更多想法

  • 您可以使用Location.getAccuracy()监视Location对象的准确性,该方法返回以米为单位的估计位置准确性。
  • Criteria.ACCURACY_HIGH标准应为您提供100m以下的误差,虽然误差不如GPS,但可以满足您的需求。
  • 您还需要监视位置提供程序的状态,如果用户不可用或禁用它,请切换到其他提供程序。
  • 被动提供商也可能是这种应用的良好匹配:这个想法是利用位置更新时,他们被另一个应用程序和广播系统范围的要求。

我已经调查过,Criteria但是如果最新的网络位置很棒(它可以通过wifi知道),而又不需要时间或电池来获取它(getLastKnown),那么标准可能会忽略它并返回GPS。我不敢相信Google对开发人员来说很难。
Nicklas A.

除了使用条件之外,您还可以在所选提供商提供的每个位置更新中,检查GPS提供商的lastKnowLocation并将其(准确度和日期)与当前位置进行比较。但是在我看来,这似乎是一个不错的选择,而不是您的规格要求;如果有时可以达到更高的精度,对您的用户真的有用吗?
斯特凡

那就是我现在正在做的,问题是我很难弄清楚最后的知识是否足够好。我还可以补充一点,我不必局限于一个提供者,我使用的次数越多,锁就越快。
Nicklas A.

请记住,PASSIVE_PROVIDER需要API级别8或更高。
爱德华多

@Stéphane抱歉,无法进行编辑。不要照顾它。您的帖子是正确的。我做了错误的编辑。抱歉。问候。
高乔(Gaucho),

10

回答前两点

  • 如果启用了GPS 并且周围没有厚墙,GPS将始终为您提供更精确的位置。

  • 如果位置未更改,则可以调用getLastKnownLocation(String)并立即检索位置。

使用替代方法

您可以尝试获取正在使用的小区ID或所有相邻小区

TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation loc = (GsmCellLocation) mTelephonyManager.getCellLocation(); 
Log.d ("CID", Integer.toString(loc.getCid()));
Log.d ("LAC", Integer.toString(loc.getLac()));
// or 
List<NeighboringCellInfo> list = mTelephonyManager.getNeighboringCellInfo ();
for (NeighboringCellInfo cell : list) {
    Log.d ("CID", Integer.toString(cell.getCid()));
    Log.d ("LAC", Integer.toString(cell.getLac()));
}

然后,您可以通过几个打开的数据库(例如,http : //www.location-api.com/http://opencellid.org/)来引用单元位置。


该策略将是在读取位置时读取塔ID列表。然后,在下一个查询中(在您的应用中10分钟),再次阅读它们。如果至少有一些塔是相同的,则可以安全使用getLastKnownLocation(String)。如果不是,请等待onLocationChanged()。这避免了该位置需要第三方数据库。您也可以尝试这种方法


是的,但是如果lastKnownLocation真的不好,问题就来了。我需要一种决定两个位置中最佳位置的好方法。
Nicklas A.

您可以存储塔的信息并检查这些塔是否已更改。如果是这样,则等待一个新的位置,如果没有(或者只有一些更改),则重新使用它。这样,您可以避免将塔架位置与数据库进行比较。
2011年

对我来说,使用塔似乎是一个很大的矫over过正,尽管是个好主意。
Nicklas A.

@Nicklas的代码没有比这更复杂的了。不过,您将需要android.Manifest.permission#ACCESS_COARSE_UPDATES。
阿莱丹2011年

是的,但是我仍然需要使用第三方服务,并且还需要一种方法来决定何时通过位置数据使用塔式信息,这只会增加一层额外的复杂性。
Nicklas A.

9

这是我的解决方案,效果很好:

private Location bestLocation = null;
private Looper looper;
private boolean networkEnabled = false, gpsEnabled = false;

private synchronized void setLooper(Looper looper) {
    this.looper = looper;
}

private synchronized void stopLooper() {
    if (looper == null) return;
    looper.quit();
}

@Override
protected void runTask() {
    final LocationManager locationManager = (LocationManager) service
            .getSystemService(Context.LOCATION_SERVICE);
    final SharedPreferences prefs = getPreferences();
    final int maxPollingTime = Integer.parseInt(prefs.getString(
            POLLING_KEY, "0"));
    final int desiredAccuracy = Integer.parseInt(prefs.getString(
            DESIRED_KEY, "0"));
    final int acceptedAccuracy = Integer.parseInt(prefs.getString(
            ACCEPTED_KEY, "0"));
    final int maxAge = Integer.parseInt(prefs.getString(AGE_KEY, "0"));
    final String whichProvider = prefs.getString(PROVIDER_KEY, "any");
    final boolean canUseGps = whichProvider.equals("gps")
            || whichProvider.equals("any");
    final boolean canUseNetwork = whichProvider.equals("network")
            || whichProvider.equals("any");
    if (canUseNetwork)
        networkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (canUseGps)
        gpsEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // If any provider is enabled now and we displayed a notification clear it.
    if (gpsEnabled || networkEnabled) removeErrorNotification();
    if (gpsEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER));
    if (networkEnabled)
        updateBestLocation(locationManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
    if (desiredAccuracy == 0
            || getLocationQuality(desiredAccuracy, acceptedAccuracy,
                    maxAge, bestLocation) != LocationQuality.GOOD) {
        // Define a listener that responds to location updates
        LocationListener locationListener = new LocationListener() {

            public void onLocationChanged(Location location) {
                updateBestLocation(location);
                if (desiredAccuracy != 0
                        && getLocationQuality(desiredAccuracy,
                                acceptedAccuracy, maxAge, bestLocation)
                                == LocationQuality.GOOD)
                    stopLooper();
            }

            public void onProviderEnabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled =true;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = true;
                // The user has enabled a location, remove any error
                // notification
                if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }

            public void onProviderDisabled(String provider) {
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER))networkEnabled=false;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER)) gpsEnabled = false;
                if (!gpsEnabled && !networkEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
            }

            public void onStatusChanged(String provider, int status,
                    Bundle extras) {
                Log.i(LOG_TAG, "Provider " + provider + " statusChanged");
                if (isSameProvider(provider,
                        LocationManager.NETWORK_PROVIDER)) networkEnabled = 
                        status == LocationProvider.AVAILABLE
                        || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                else if (isSameProvider(provider,
                        LocationManager.GPS_PROVIDER))
                    gpsEnabled = status == LocationProvider.AVAILABLE
                      || status == LocationProvider.TEMPORARILY_UNAVAILABLE;
                // None of them are available, stop listening
                if (!networkEnabled && !gpsEnabled) {
                    showErrorNotification();
                    stopLooper();
                }
                // The user has enabled a location, remove any error
                // notification
                else if (canUseGps && gpsEnabled || canUseNetwork
                        && networkEnabled) removeErrorNotification();
            }
        };
        if (networkEnabled || gpsEnabled) {
            Looper.prepare();
            setLooper(Looper.myLooper());
            // Register the listener with the Location Manager to receive
            // location updates
            if (canUseGps)
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            if (canUseNetwork)
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 1000, 1,
                        locationListener, Looper.myLooper());
            Timer t = new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    stopLooper();
                }
            }, maxPollingTime * 1000);
            Looper.loop();
            t.cancel();
            setLooper(null);
            locationManager.removeUpdates(locationListener);
        } else // No provider is enabled, show a notification
        showErrorNotification();
    }
    if (getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
            bestLocation) != LocationQuality.BAD) {
        sendUpdate(new Event(EVENT_TYPE, locationToString(desiredAccuracy,
                acceptedAccuracy, maxAge, bestLocation)));
    } else Log.w(LOG_TAG, "LocationCollector failed to get a location");
}

private synchronized void showErrorNotification() {
    if (notifId != 0) return;
    ServiceHandler handler = service.getHandler();
    NotificationInfo ni = NotificationInfo.createSingleNotification(
            R.string.locationcollector_notif_ticker,
            R.string.locationcollector_notif_title,
            R.string.locationcollector_notif_text,
            android.R.drawable.stat_notify_error);
    Intent intent = new Intent(
            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    ni.pendingIntent = PendingIntent.getActivity(service, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    Message msg = handler.obtainMessage(ServiceHandler.SHOW_NOTIFICATION);
    msg.obj = ni;
    handler.sendMessage(msg);
    notifId = ni.id;
}

private void removeErrorNotification() {
    if (notifId == 0) return;
    ServiceHandler handler = service.getHandler();
    if (handler != null) {
        Message msg = handler.obtainMessage(
                ServiceHandler.CLEAR_NOTIFICATION, notifId, 0);
        handler.sendMessage(msg);
        notifId = 0;
    }
}

@Override
public void interrupt() {
    stopLooper();
    super.interrupt();
}

private String locationToString(int desiredAccuracy, int acceptedAccuracy,
        int maxAge, Location location) {
    StringBuilder sb = new StringBuilder();
    sb.append(String.format(
            "qual=%s time=%d prov=%s acc=%.1f lat=%f long=%f",
            getLocationQuality(desiredAccuracy, acceptedAccuracy, maxAge,
                    location), location.getTime() / 1000, // Millis to
                                                            // seconds
            location.getProvider(), location.getAccuracy(), location
                    .getLatitude(), location.getLongitude()));
    if (location.hasAltitude())
        sb.append(String.format(" alt=%.1f", location.getAltitude()));
    if (location.hasBearing())
        sb.append(String.format(" bearing=%.2f", location.getBearing()));
    return sb.toString();
}

private enum LocationQuality {
    BAD, ACCEPTED, GOOD;

    public String toString() {
        if (this == GOOD) return "Good";
        else if (this == ACCEPTED) return "Accepted";
        else return "Bad";
    }
}

private LocationQuality getLocationQuality(int desiredAccuracy,
        int acceptedAccuracy, int maxAge, Location location) {
    if (location == null) return LocationQuality.BAD;
    if (!location.hasAccuracy()) return LocationQuality.BAD;
    long currentTime = System.currentTimeMillis();
    if (currentTime - location.getTime() < maxAge * 1000
            && location.getAccuracy() <= desiredAccuracy)
        return LocationQuality.GOOD;
    if (acceptedAccuracy == -1
            || location.getAccuracy() <= acceptedAccuracy)
        return LocationQuality.ACCEPTED;
    return LocationQuality.BAD;
}

private synchronized void updateBestLocation(Location location) {
    bestLocation = getBestLocation(location, bestLocation);
}

protected Location getBestLocation(Location location,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return location;
    }
    if (location == null) return currentBestLocation;
    // 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 location;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }
    // 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 location;
    } else if (isNewer && !isLessAccurate) {
        return location;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return location;
    }
    return bestLocation;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) return provider2 == null;
    return provider1.equals(provider2);
}

嗨尼克拉斯我有同样的equirement所以我可以以任何方式与您沟通。我会,如果你能充分感谢你帮助我们。
读书郎

您可以发布整个代码吗?谢谢,非常感谢
Rodi 2014年

这就是所有代码。我再也无法访问该项目。
Nicklas A. 2014年

1
您似乎已经采用了该项目的代码“ android-protips-location”,并且该代码仍然有效。人们可以看到它是如何在这里工作code.google.com/p/android-protips-location/source/browse/trunk/...
Gödel77

7

位置精度主要取决于所使用的位置提供商:

  1. GPS-可以使您获得几米的精度(假设您具有GPS接收功能)
  2. Wifi-将使您达到几百米的精度
  3. 小区网络-会给您非常不准确的结果(我看过4公里的偏差...)

如果您正在寻找精度,那么GPS是您唯一的选择。

我读过关于它的内容非常丰富的文章在这里

至于GPS超时-60秒就足够了,在大多数情况下甚至太多了。我认为30秒还可以,有时甚至不到5秒...

如果您只需要一个位置,我建议您在onLocationChanged方法中,一旦收到更新,便要注销监听器,并避免不必要地使用GPS。


我真的不在乎从哪里获得我的位置,我也不想将我限制在一个提供者
Nicklas A.

您可以注册设备上所有可用的位置提供程序(可以从LocationManager.getProviders()获取所有提供程序的列表),但是如果您要查找准确的修补程序,则在大多数情况下,网络提供程序对您没有用。
Muzikant 2011年

是的,但这不是关于在提供商之间进行选择的问题,这是关于通常获得最佳位置的问题(即使涉及多个提供商)
Nicklas A.

4

当前我正在使用,因为这对于获取我的应用程序的位置和计算距离是值得信赖的……我正在将其用于我的出租车应用程序。

使用Google开发人员通过将GPS传感器,磁力仪,加速度计融合在一起而开发的融合API,还使用Wifi或单元位置来计算或估算位置。它还能够准确地在建筑物内部提供位置更新。有关详细信息,请链接到 https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi

import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class MainActivity extends Activity implements LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final long ONE_MIN = 500;
    private static final long TWO_MIN = 500;
    private static final long FIVE_MIN = 500;
    private static final long POLLING_FREQ = 1000 * 20;
    private static final long FASTEST_UPDATE_FREQ = 1000 * 5;
    private static final float MIN_ACCURACY = 1.0f;
    private static final float MIN_LAST_READ_ACCURACY = 1;

    private LocationRequest mLocationRequest;
    private Location mBestReading;
TextView tv;
    private GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!servicesAvailable()) {
            finish();
        }

        setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.tv1);
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(POLLING_FREQ);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();


        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onPause() {d
        super.onPause();

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }


        tv.setText(location + "");
        // Determine whether new location is better than current best
        // estimate
        if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) {
            mBestReading = location;


            if (mBestReading.getAccuracy() < MIN_ACCURACY) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            }
        }
    }

    @Override
    public void onConnected(Bundle dataBundle) {
        // Get first reading. Get additional location updates if necessary
        if (servicesAvailable()) {

            // Get best last location measurement meeting criteria
            mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);

            if (null == mBestReading
                    || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY
                    || mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) {

                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

               //Schedule a runnable to unregister location listeners

                    @Override
                    public void run() {
                        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MainActivity.this);

                    }

                }, ONE_MIN, TimeUnit.MILLISECONDS);

            }

        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }


    private Location bestLastKnownLocation(float minAccuracy, long minTime) {
        Location bestResult = null;
        float bestAccuracy = Float.MAX_VALUE;
        long bestTime = Long.MIN_VALUE;

        // Get the best most recent location currently available
        Location mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        //tv.setText(mCurrentLocation+"");
        if (mCurrentLocation != null) {
            float accuracy = mCurrentLocation.getAccuracy();
            long time = mCurrentLocation.getTime();

            if (accuracy < bestAccuracy) {
                bestResult = mCurrentLocation;
                bestAccuracy = accuracy;
                bestTime = time;
            }
        }

        // Return best reading or null
        if (bestAccuracy > minAccuracy || bestTime < minTime) {
            return null;
        }
        else {
            return bestResult;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    private boolean servicesAvailable() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

        if (ConnectionResult.SUCCESS == resultCode) {
            return true;
        }
        else {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0).show();
            return false;
        }
    }
}

2

我使用Google建议的最新位置提取方法(使用FusedLocationProviderClient)在Internet上搜索了更新的(去年)答案。我终于找到了这个:

https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates

我创建了一个新项目,并复制了大部分代码。繁荣。有用。而且我认为没有任何过时的行。

另外,据我所知,模拟器似乎并没有获得GPS位置。它的确做到了在日志中报告这一点:“满足所有位置设置”。

最后,如果您想知道(我知道),则不需要从Google开发人员控制台获取google maps api密钥,如果您想要的只是GPS位置。

他们的教程也很有用。但是我想要一个完整的一页教程/代码示例,等等。他们的教程堆栈很多,但是当您不熟悉它时会感到困惑,因为您不知道以前的页面需要什么。

https://developer.android.com/training/location/index.html

最后,请记住以下内容:

我不仅不得不修改mainActivity.Java。我还必须修改Strings.xml,androidmanifest.xml和正确的build.gradle。还有您的activity_Main.xml(但这对我来说很容易)。

我需要添加如下所示的依赖项:实现'com.google.android.gms:play-services-location:11.8.0',并更新我的android studio SDK的设置以包括google play服务。(文件设置外观系统设置android SDK SDK Tools检查Google Play服务)。

更新:android模拟器似乎确实获得了位置和位置更改事件(当我更改sim的设置中的值时)。但是我最好的结果是在实际设备上。因此,在实际设备上进行测试可能是最简单的。


1

最近重构以获得代码的位置,学习了一些好主意,最后实现了一个相对完善的库和Demo。

@Gryphius的答案很好

    //request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
    checkRuntimeEnvironment();
    checkPermission();

    if (isRequesting) {
        EasyLog.d("Request location update is busy");
        return false;
    }


    long minTime = getCheckTimeInterval();
    float minDistance = getCheckMinDistance();

    if (mMapLocationListeners == null) {
        mMapLocationListeners = new HashMap<>();
    }

    mValidProviders = getValidProviders();
    if (mValidProviders == null || mValidProviders.isEmpty()) {
        throw new IllegalArgumentException("Not available provider.");
    }

    for (String provider : mValidProviders) {
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location == null) {
                    EasyLog.e("LocationListener callback location is null.");
                    return;
                }
                printf(location);
                mLastProviderTimestamp = location.getTime();

                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    finishResult(location);
                } else {
                    doLocationResult(location);
                }

                removeProvider(location.getProvider());
                if (isEmptyValidProviders()) {
                    requestTimeoutMsgInit();
                    removeUpdates();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
        mMapLocationListeners.put(provider, locationListener);
        EasyLog.d("Location request %s provider update.", provider);
    }
    isRequesting = true;
    return true;
}

//remove request update
public void removeUpdates() {
    checkRuntimeEnvironment();

    LocationManager locationManager = getLocationManager();
    if (mMapLocationListeners != null) {
        Set<String> keys = mMapLocationListeners.keySet();
        for (String key : keys) {
            LocationListener locationListener = mMapLocationListeners.get(key);
            if (locationListener != null) {
                locationManager.removeUpdates(locationListener);
                EasyLog.d("Remove location update, provider is " + key);
            }
        }
        mMapLocationListeners.clear();
        isRequesting = false;
    }
}

//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
    checkLocation(location);

    if (mLastLocation != null) {
        float distance = location.distanceTo(mLastLocation);
        if (distance < getCheckMinDistance()) {
            return true;
        }
        if (location.getAccuracy() >= mLastLocation.getAccuracy()
                && distance < location.getAccuracy()) {
            return true;
        }
        if (location.getTime() <= mLastProviderTimestamp) {
            return true;
        }
    }
    return false;
}

private void doLocationResult(Location location) {
    checkLocation(location);

    if (isNeedFilter(location)) {
        EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
        finishResult(mLastLocation);
    } else {
        finishResult(location);
    }
}

//Return to the finished position
private void finishResult(Location location) {
    checkLocation(location);

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float accuracy = location.getAccuracy();
    long time = location.getTime();
    String provider = location.getProvider();

    if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
        String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
        EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));

        mLastLocation = location;
        synchronized (this) {
            Iterator<LocationResultListener> iterator =  mLocationResultListeners.iterator();
            while (iterator.hasNext()) {
                LocationResultListener listener = iterator.next();
                if (listener != null) {
                    listener.onResult(location);
                }
                iterator.remove();
            }
        }
    }
}

完整的实现:https : //github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java

1.感谢@Gryphius解决方案的想法,我也分享了完整的代码。

2.每次请求完成位置后,最好删除更新,否则手机状态栏将始终显示定位图标


0

根据我的经验,我发现最好使用GPS修复程序,除非它不可用。我对其他定位服务提供商了解不多,但是我知道对于GPS,有一些技巧可以用来进行贫民窟改造的精确度测量。高度通常是一个标志,因此您可以检查可笑的值。Android定位修复程序有精度度量。另外,如果您可以看到所用卫星的数量,则也可以指示精度。

更好地了解准确性的一种有趣方法是非常快速地请求一组修复程序,例如〜1 / sec持续10秒,然后睡眠一两分钟。我去过的一个话题使人们相信某些android设备仍然可以做到这一点。然后,您将剔除异常值(我听说过这里提到的卡尔曼滤波器),并使用某种对中策略来获得单个修正。

显然,您到达这里的深度取决于您的要求有多难。如果您对获得最佳位置的要求特别严格,我想您会发现GPS和网络位置与苹果和橘子一样。GPS可能因设备而异。


好吧,最好是最好的,这并不重要,因为它足以在地图上绘制,并且我不消耗电池,因为这是一项后台任务。
Nicklas A.

-3

Skyhook(http://www.skyhookwireless.com/)的位置提供商比Google提供的标准要快得多。这可能是您要寻找的。我不隶属于他们。


确实有趣的是,他们似乎只使用WiFi,但这非常好,但是当周围没有wifi或3G / 2G连接时,我仍然需要它工作,因此这将增加另一层抽象。虽然好捕获。
Nicklas A.

1
Skyhook似乎结合使用了WiFi,GPS和手机信号塔。有关技术细节,请参见skyhookwireless.com/howitworks。他们最近获得了多项设计大奖,例如Mapquest,Twydroid,ShopSavvy和Sony NGP。请注意,下载和试用其SDK似乎是免费的,但您必须与他们联系以获取在您的应用程序中分发它的许可证。不幸的是,他们没有在其网站上列出价格。
Ed Burnette

哦,我明白了。好吧,如果它不是免费用于商业用途,那么恐怕我不能使用它。
Nicklas A.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.