在 Android 上获取用户当前位置的最简单、最可靠的方法是什么? [英] What is the simplest and most robust way to get the user's current location on Android?

查看:32
本文介绍了在 Android 上获取用户当前位置的最简单、最可靠的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android 上的 LocationManager API 对于只需要偶尔粗略估计用户位置的应用程序来说似乎有点麻烦.

The LocationManager API on Android seems like it's a bit of a pain to use for an application that only needs an occasional and rough approximation of the user's location.

我正在开发的应用本身并不是真正的位置应用,但它确实需要获取用户的位置才能显示附近企业的列表.它不需要担心用户是否四处走动或类似的事情.

The app I'm working on isn't really a location app per se, but it does need to get the user's location in order to display a list of nearby businesses. It doesn't need to worry about if the user is moving around or anything like that.

这是我想要做的:

  1. 向用户显示附近位置的列表.
  2. 预加载用户的位置,以便我在 Activity X 中需要它时,它就会可用.
  3. 我并不特别关心更新的准确性或频率.只要不远,只需抓住一个位置就足够了.也许如果我想变得更漂亮,我会每隔几分钟左右更新一次位置,但这不是一个重要的优先事项.
  4. 适用于任何具有 GPS 或网络位置提供商的设备.
  1. Show the user a list of nearby locations.
  2. Preload the user's location so that by the time I need it in Activity X, it will be available.
  3. I don't particularly care about accuracy or frequency of update. Just grabbing one location is sufficient as long as it's not way off. Maybe if I want to be fancy I'll update the location once every few mins or so, but it's not a huge priority.
  4. Work for any device as long as it has either a GPS or a Network Location provider.

看起来不应该那么难,但在我看来,我必须启动两个不同的位置提供程序(GPS 和 NETWORK)并管理每个的生命周期.不仅如此,我还必须在多个活动中复制相同的代码才能满足 #2.我过去曾尝试使用 getBestProvider() 将解决方案缩减为仅使用一个位置提供程序,但这似乎只能为您提供最佳的理论"提供程序,而不是实际运行的提供程序为您提供最佳结果.

It seems like it shouldn't be that hard, but it appears to me that I have to spin up two different location providers (GPS and NETWORK) and manage each's lifecycle. Not only that, but I have to duplicate the same code in multiple activities to satisfy #2. I've tried using getBestProvider() in the past to cut the solution down to just using one location provider, but that seems to only give you the best "theoretical" provider rather than the provider that's actually going to give you the best results.

有没有更简单的方法来实现这一点?

Is there a simpler way to accomplish this?

推荐答案

这是我的工作:

  1. 首先,我检查启用了哪些提供程序.有些可能在设备上被禁用,有些可能在应用清单中被禁用.
  2. 如果有任何提供者可用,我会启动位置侦听器和超时计时器.在我的示例中为 20 秒,对于 GPS 而言可能不够,因此您可以将其放大.
  3. 如果我从位置侦听器获得更新,我将使用提供的值.我停止监听器和计时器.
  4. 如果我没有收到任何更新并且计时器已过,我就必须使用最新的已知值.
  5. 我从可用的提供者那里获取最新的已知值并选择最近的值.

这是我如何使用我的课程:

Here's how I use my class:

LocationResult locationResult = new LocationResult(){
    @Override
    public void gotLocation(Location location){
        //Got the location!
    }
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

这是 MyLocation 类:

And here's MyLocation class:

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 20000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

可能有人还想修改我的逻辑.例如,如果您从网络提供商处获得更新,请不要停止侦听器而是继续等待.GPS 提供更准确的数据,因此值得等待.如果计时器已过并且您已从网络获得更新但未从 GPS 获得更新,则您可以使用网络提供的值.

Somebody may also want to modify my logic. For example if you get update from Network provider don't stop listeners but continue waiting. GPS gives more accurate data so it's worth waiting for it. If timer elapses and you've got update from Network but not from GPS then you can use value provided from Network.

另一种方法是使用 LocationClient http://developer.android.com/training/location/retrieve-current.html.但它需要在用户设备上安装 Google Play Services apk.

One more approach is to use LocationClient http://developer.android.com/training/location/retrieve-current.html. But it requires Google Play Services apk to be installed on user device.

这篇关于在 Android 上获取用户当前位置的最简单、最可靠的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆