安卓系统中的“我的位置”定位问题解决方案

6
当调用我的地图活动时,我会在onCreate中调用addUserMapPoint。该功能包含两个实例,其中我尝试使用myOverlay.getMyLocation获取位置信息。在此活动的初始加载中,第一次尝试的结果返回null GeoPoint,并且在主UI线程完成后,在myOverlay.runOnFirstFix(new Runnable()…)的侦听器线程中调用的第二次尝试在一秒钟后被调用,它包含一个包含lat和lon的GeoPoint。此侦听函数内部的调用似乎将点放在地图上,线mapController.animateTo(gp)将地图移动到我的位置。我的应用程序有一个刷新按钮,当单击时再次触发此活动。为了从另一个服务获取位置数据,我需要纬度和经度。刷新后,通过地图活动代码的第二次访问,我希望第一次调用myOverlay.getMyLocation()现在能够获取GeoPoint,但它仍然为空。
如果我无法通过第一次调用myOverlay.getMyLocation获取GeoPoint,则如何传递找到的lat和lon值(位于myOverlay.runOnFirstFix(new Runnable()… )线程中)?您会注意到,我一直在尝试将lat和lon添加到MyApp中,这是helper bean类,但即使在刷新后,该类中的lat和lon也为空。如果在第一次访问该活动时手动设置纬度和经度,则保留这些值。我猜这是因为它在主UI线程上设置。
public class MapActivity extends com.google.android.maps.MapActivity {
    private MapView mapView = null;
    private MapController mapController = null;
    private MyLocationOverlay myOverlay = null;

    public static MyApp app;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        app = (MyApp) getApplicationContext();

        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();

        List<Overlay> mapOverlays = mapView.getOverlays();
        mapOverlays.clear();

        addUserMapPoint(mapView);

        if (!app.isLocServOff()) {
            //map other points – service call to get items from our service near lat and lon
            addOtherMapPoints(mapOverlays);

        } else {
            Toast.makeText(app.getApplicationContext(),"Current location could not be found.",Toast.LENGTH_LONG).show();
        }

    }

    private void addUserMapPoint(MapView mapView){
            myOverlay = new MyLocationOverlay(app.getApplicationContext(), mapView);
            myOverlay.disableCompass();
        myOverlay.enableMyLocation();


            if(app.getMyLat()==null||app.getMyLon()==null){
                GeoPoint gp = myOverlay.getMyLocation();
                if(gp!=null){
                    app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                    app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                    app.setLocServOff(false);
                }else{
                    app.setLocServOff(true);
                }
        }


        myOverlay.runOnFirstFix(new Runnable() {   
                public void run() {     
                    GeoPoint gp = myOverlay.getMyLocation();    
                    if(gp!=null){
                        app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                        app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                        app.setLocServOff(false);   
                        mapController.animateTo(gp);
                    }else{
                        app.setLocServOff(true);
                    }
                }    
            });

        mapView.getOverlays().add(myOverlay);
    }   

}

下面是您需要翻译的内容:

我需要在主UI线程中获取包含经纬度的GeoPoint,或者从myOverlay.runOnFirstFix(new Runnable()…线程中获得GeoPoint并传递这些值。如果您建议我使用Handler或runOnUiThread,请提供代码示例,将lat和lon回传到可以被主UI线程/地图视图使用的内容中。我尝试过以下代码,但未能产生期望的结果。虽然我能够让Toast消息显示出来,但无法以可用的方式传递经纬度。


格式要求: 请直接返回翻译后的文本内容,不需要任何标签和解释。
    final Handler handler = new Handler();   
    myOverlay.runOnFirstFix(new Runnable() {                     
        @Override public void run() {

            handler.post(new Runnable() {                                   
                @Override public void run() {

                        GeoPoint gp = myOverlay.getMyLocation();    
                        if(gp!=null){
                            app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                            app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                            app.setLocServOff(false);   
                            mapController.animateTo(gp);                                

                        }else{
                            app.setLocServOff(true);
                        }

                    //Toast.makeText(getApplicationContext(),"wowoowowowoowoowowow",Toast.LENGTH_LONG).show();                      
                    }                                  
                });

            }                
        }); 

我之前也使用了类似以下代码来获取纬度和经度,它是有效的。但由于当前位置有时会与返回的纬度和经度不同,因为例如我无法获得GPS信号而返回一个旧值。我添加了检查,以查看纬度/经度数据是否超过2分钟未更新,但仍然无法将最新的纬度和经度与myOverlay.getMyLocation返回的值匹配。

    LocationManager locMgr = (LocationManager)appcontext.getSystemService(Context.LOCATION_SERVICE);
    MyLocationListener locLstnr = new MyLocationListener();

    //fetch current location for current location 
    locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locLstnr, appcontext.getMainLooper());  
5个回答

3
以下是如何在UI线程中获取当前位置的一些示例,但首先需要了解一些背景信息。
GPS可能需要一些时间(15秒至1分钟)才能在请求新位置后获得第一个修复程序。这就是您从myOverlay尝试首次获取它失败的原因,只有在第一个修复程序之后,您才可以获取该值。
在此“黑暗期间”,如果您急需使用,则可以使用getLastKnownLocation()获取最后已知的良好GPS位置。如果不可用,则返回null。
代码:
最后已知位置
LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null){
    //we have a valid location. Check location date
}

请求单个位置更新

LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, appcontext.getMainLooper);

请求持续位置更新

LocationManager locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//use 0 for minDistance and minDistance between updates if you need the maximum update frequency.
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minDistance, minTime, locationListener);

单次和连续位置更新的位置监听器

这是最后一部分代码,也是您获取上述请求的新鲜位置的地方。

当 GPS 检索到满足您上述定义的请求标准的新位置时,立即调用此侦听器,除非您的设备正在忙于执行无法中断的其他操作(即回调在暂停的线程上或遇到锁)。

onLocationChanged() 中,您可以根据需要设置任何类级字段。如果您从 UI 线程注册了侦听器,则此代码将在 UI 上运行。

LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location fix) {
        fix.setTime(fix.getTime() + timeZoneOffset); //Add Timezone offset if needed
        //here you have a fresh new location in fix...
        //You can set the value of any class level field from here
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

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

敬礼。


2
在寻找设备位置时,您必须考虑以下一些最重要的问题:
  1. 不能保证在足够的时间内接收到卫星GPS信号。例如,设备在建筑物内或不在开阔天空下。
  2. 确保卫星GPS监听器没有长时间保持活动状态。保持监听器处于开启状态将意味着始终保持GPS电台开启,成为最大的电池耗尽原因。
在下面的代码示例中,LinkedBlockingQueue中的轮询方法不会返回,直到指定的时间间隔已过或位置已排队。
使用类似以下内容以获取当前位置:
    Location getCurrentLocation() {
    long startmillis = 0;
    LinkedBlockingQueue<Location> mQueue = new LinkedBlockingQueue<Location>();
            try{


                long millisSinceLastCollection = System.currentTimeMillis() - startmillis; 


                startmillis = System.currentTimeMillis();
                mQueue.clear();

    // Register for Satellite GPS listener as well as Network GPS listener.
                registerGPSListeners();

                // Wait for a maximum of one minutes for a fix
                Location firstfix = mQueue.poll(1, TimeUnit.MINUTES);


                if(firstfix != null && firstfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    return firstfix;
                }

                long elapsedmillis = System.currentTimeMillis() - startmillis;
                long remainingmillis = ONE_MINUTE_IN_MS - elapsedmillis; 
                if (remainingmillis <= 0){
                    return firstfix;
                }

                Location secondfix = mQueue.poll(remainingmillis, TimeUnit.MILLISECONDS);

                if(secondfix != null && secondfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    return secondfix;
                }

                /*
                 * In case we receive fix only from Network provider, return it.
                 */
                if(firstfix != null && firstfix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
                    return firstfix;
                }

            } catch(Exception e){
                Logger.e("GPS: Exception while listening for the current location", e);
            } finally {
                Logger.i("GPS: Unsubscribing from any existing GPS listeners");
                unregisterGPSListeners();

            }
    }


// GPS issue fix edit.
    private void registerGPSListeners() {

        LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);

        if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, oneShotNetworkGPSLocationListener, MyAppApp.getAppContext().getMainLooper());

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100, oneShotSatelliteGPSLocationListener, AirWatchApp.getAppContext().getMainLooper());
        }
    }

    private void unregisterGPSListeners(){

        final LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
        locationManager.removeUpdates(oneShotSatelliteGPSLocationListener);
        locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
    }

//One shot location listener
    protected LocationListener oneShotSatelliteGPSLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            try {
                mQueue.put(location);
            } catch (InterruptedException e) {
                Logger.e("Exception in putting new Location to the queue", e);
            }

            Logger.d("GPS: Location received from Satellite GPS Provider");
            unregisterGPSListeners();
        }

        public void onProviderDisabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
    };

    //One shot location listener
    protected LocationListener oneShotNetworkGPSLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            try {
                mQueue.put(location);
            } catch (InterruptedException e) {
                Logger.e("Exception in putting new Location to the queue", e);
            }

            Logger.d("GPS: Location received from Network GPS Provider");
            // Stop Listener for one-shot location fix from Network GPS provider.
            final LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
            locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
            Logger.d("GPS: Unsubscribed the network location listener.");
        }

        public void onProviderDisabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
    };

2
handler.post(new Runnable() {                                   
            @Override public void run() {

                    GeoPoint gp = myOverlay.getMyLocation();    
                    if(gp!=null){
                        app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
                        app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
                        app.setLocServOff(false);

                        // HERE WE HAVE VALID gp VALUE AND WE NEED TO SHARE IT

                        mapController.animateTo(gp);                                

                    }else{
                        app.setLocServOff(true);
                    }
                }                                  
            });

我认为你的app.set/get|MyLat/Lon不起作用,因为你从不同的线程中调用它们。要解决这个问题,需要对MyLat/Long的set和get方法进行同步(创建一个对象进行同步并在其上同步)。
或者,如果你喜欢使用handler,可以尝试以下方法:
final Handler handler = new Handler(); // BE SURE TO RUN THIS LINE ON UI THREAD
...   
myOverlay.runOnFirstFix(new Runnable() {                     
    @Override public void run() {

        // THIS PART WORKS AS BEFORE
        final GeoPoint gp = myOverlay.getMyLocation();
        mapController.animateTo(gp);                        
        ...
        // AND THIS RUNNABLE TO UPDATE MyLat/MyLong FROM UI THREAD
        handler.post(new Runnable() {                                   
            @Override public void run() {
               app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
               app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
            });

        }                
    }); 

虽然其他人的帖子都很好,描述了如何使用GPS获取位置,但是你的帖子最直接地回答了我的问题。我能够使用“handler.post”和“run()”在我的应用程序类中填充lat和lon值,在刷新后可被我的地图活动访问。如果您有时间提供,我很想看到使用我的应用程序对象上同步的setter和getter方法来完成此操作的示例。感谢大家的贡献,祝你们新年快乐、安全! - ItBHarsH

2

Android会修改用户界面并从一个单一的用户界面线程(主线程)处理输入事件。

如果程序员不使用任何并发结构,所有Android应用程序的代码都在此线程中运行。

GPS是确定用户位置的最佳方式,但频繁向全球定位卫星发送请求会迅速耗尽移动设备的电池,获取用户位置需要很长时间,并且该方法在室内并不总是有效。 你没有在第一次尝试中获取到你的位置,这就是为什么你在那里得到了null。

Android的网络位置提供者根据基站和Wi-Fi信号确定用户的位置。它不仅比GPS使用更少的电池电量,而且速度更快,无论用户在室外还是室内都可以工作。

我在下面提供了我的工作代码,它显示进度对话框,监听用户的位置,并在获取位置后在Google地图上显示用户的位置覆盖层

我假设您已经在Menifest文件中授予以下权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
我的主要类

public class MyLocationOnMap extends MapActivity {

private MapView mapView;
private MyLocationOverlay itemizedoverlay;
private LocationManager locationManager;
private String provider;
private MyLocationListener locationListener;
MyBroadCastreceiver myBroadCastreceiver;
/**
 * My current Location <i>longitude</i>.
 */
static int longitude;
/**
 * My current Location <i>latitude</i>.
 */
static int latitude;
/**
 *My progress indicator. 
 */
ProgressDialog loadingDialog;

public static final String INTENT_FILTER_TAG="my location broadcast receiver";


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_location_on_map);

    loadingDialog = new ProgressDialog(this);
    loadingDialog.setTitle("Hot Spots!");
    loadingDialog.setMessage("Please wait ...");
    loadingDialog.setIndeterminate(true);
    loadingDialog.setCancelable(false);

    loadingDialog.show();

 // Configure the Map
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setStreetView(true);

    /**
     * Get your location manager and Location Listener...
     */
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationListener=new MyLocationListener();

    myBroadCastreceiver = new MyBroadCastreceiver();

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Log.i("GPS_Enabled", "GPS enable! listening for gps location.");
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
            registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Log.i("Network_Enabled", "Network enable! listening for Network location.");
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener);
            registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
        } else {
            loadingDialog.dismiss();
            Toast.makeText(this, "No Provider enable!", Toast.LENGTH_LONG).show();
        }

}//End of onCreate......

 /**
 * My BroadCast Receiver, that is called when i get the location of user.
 * @author Rupesh Yadav.
 *
 */
class MyBroadCastreceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        //Remove location update when you get user`s location very first time.
        locationManager.removeUpdates(locationListener);
        //Remove the broadcast listener that update my location on map.
        unregisterReceiver(myBroadCastreceiver);

        GeoPoint point = new GeoPoint(latitude, longitude);
        mapView.getController().animateTo(point);

        List<Overlay> mapOverlays = mapView.getOverlays();
        Drawable drawable = MyLocationOnMap.this.getResources().getDrawable(R.drawable.hs_mapoverlay);
        itemizedoverlay = new MyLocationOverlay(drawable, MyLocationOnMap.this);

        OverlayItem overlayitem = new OverlayItem(point, "Hello!", "My Current Location :)");

        itemizedoverlay.addOverlay(overlayitem);
        mapOverlays.add(itemizedoverlay);

        loadingDialog.dismiss();

    }

}

/**
 * My Location listener...
 */
class MyLocationListener implements LocationListener{
    @Override
    public void onLocationChanged(Location location) {
        latitude=(int) ((location.getLatitude())*1E6);
        longitude=(int) ((location.getLongitude())*1E6);

        //Send broadcast to update my location.
        Intent sendLocationIntent=new Intent(INTENT_FILTER_TAG);
        sendBroadcast(sendLocationIntent);
    }
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

}

MyLocationOverlay class

public class MyLocationOverlay extends ItemizedOverlay<OverlayItem> {

Context mContext;
private ArrayList<OverlayItem> hsOverlays = new ArrayList<OverlayItem>();

public MyLocationOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
    // TODO Auto-generated constructor stub
}

public MyLocationOverlay(Drawable defaultMarker, Context context) {
    super(boundCenterBottom(defaultMarker));
    mContext = context;
}

@Override
protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return hsOverlays.get(i);
}

@Override
public int size() {
    // TODO Auto-generated method stub
    return hsOverlays.size();
}

/**
 * add new OverlayItem objects to map OverlayItem ArrayList.
 * 
 * @param overlay
 */
public void addOverlay(OverlayItem overlay) {
    hsOverlays.add(overlay);
    populate();
}

/**
 * Called when user clicks on map overlay.
 */
@Override
protected boolean onTap(int index) {
    // TODO Auto-generated method stub
    // return super.onTap(index);
    OverlayItem item = hsOverlays.get(index);
    AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
    dialog.setTitle(item.getTitle());
    dialog.setMessage(item.getSnippet());
    dialog.show();
    return true;
}

你可以根据自己的需求修改位置监听器广播接收器。 希望这能解决你的问题。
最好的问候!

2
我使用这个类来检测我的纬度和经度: 希望这对你也有用。
如何使用的示例: GPSUtility.getInstance(Context).getLatitude(); GPSUtility.getInstance(CamPhotoModeAct.this).getLongitude()
public class GPSUtility {
    public static final String TAG = "GPSUtility";

    private Context ctx;

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    private double latitude;
    private double longitude;

    private static SharedPreferences SHARED_PREF;
    private static SharedPreferences.Editor EDITOR_SHARED_PREF;

    private static GPSUtility this_instance;

    public GPSUtility(Context ctx){
        this.ctx = ctx;
        SHARED_PREF = ctx.getSharedPreferences(ConstantsG.SHARED_PREF_FILE, Context.MODE_PRIVATE);
        EDITOR_SHARED_PREF = SHARED_PREF.edit();
        this.getLocation(innerLocationResult);
    }

    public static GPSUtility getInstance(Context ctx){
        if(this_instance == null)
            this_instance = new GPSUtility(ctx);
        return this_instance;
    }

    public static void updateLocation(Context ctx){
        GPSUtility.getInstance(ctx);//this writes the latitude and longitude in sharable preference file
    }

    public double getLatitude(){
        String latitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LATITUDE,null);
        if(latitudeStr == null){
            latitude = 0.0;
        }
        else{
            latitude = Double.parseDouble(latitudeStr);
        }
        return latitude;
    }

    public double getLongitude(){
        String longitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LONGITUDE,null);
        if(longitudeStr == null){
            longitude = 0.0;
        }
        else{
            longitude = Double.parseDouble(longitudeStr);
        }
        return longitude;
    }

    private void updateWithNewLocation(Location location) {

        if (location != null) {
            latitude = location.getLatitude();
            EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LATITUDE, String.valueOf(latitude) );

            longitude = location.getLongitude();
            EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LONGITUDE, String.valueOf(longitude));

            EDITOR_SHARED_PREF.commit();
        }
    }

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

        //exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
        }

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled){
            Toast.makeText(this.ctx, "You should enable gps or be connected to network.", Toast.LENGTH_LONG).show();
            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(), 10000);
        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() {
            //Context context = getClass().getgetApplicationContext();
             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);
    }

    LocationResult innerLocationResult = new LocationResult() {
        @Override
        public void gotLocation(Location location) {
            updateWithNewLocation(location);
        }
    };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接