乱世@小熊 2010-06-29 21:59 采纳率: 25%
浏览 694
已采纳

在 Android 上获取用户当前位置的最简单和最强大的方法是什么?

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.

Here's what I'd like to do:

  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.

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?

转载于:https://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-on-a

  • 写回答

25条回答 默认 最新

  • Didn"t forge 2010-06-30 00:07
    关注

    Here's what I do:

    1. First of all I check what providers are enabled. Some may be disabled on the device, some may be disabled in application manifest.
    2. If any provider is available I start location listeners and timeout timer. It's 20 seconds in my example, may not be enough for GPS so you can enlarge it.
    3. If I get update from location listener I use the provided value. I stop listeners and timer.
    4. If I don't get any updates and timer elapses I have to use last known values.
    5. I grab last known values from available providers and choose the most recent of them.

    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);
    

    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);
        }
    }
    

    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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(24条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)