3

我正在使用这篇文章:在 Android 上获取用户当前位置的最简单、最可靠的方法是什么? 获取设备的当前位置。我的代码是:

locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

        }
    };

    myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);
    mapController = mapView.getController();
    point = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
    mapController.animateTo(point);
    Toast.makeText(getApplicationContext(), ("Latitude = "+latitude+" Longitude = "+longitude), Toast.LENGTH_SHORT).show();
    mapController.setZoom(17);
    mapView.invalidate();

纬度和经度被声明为全局双精度类型变量。但是,运行应用程序后,我得到了蓝屏。我认为,问题是我的代码无法获得纬度和经度的值。有人可以帮我吗?谢谢 。

4

1 回答 1

4

您的问题没有让我感觉到您的代码有什么问题,但是如果您确实需要获取设备的当前位置,我可以给您一个提示。

提示:尝试使用位置监听器,如果您的设备位置发生变化,它将为您提供纬度和经度值。

代码:

您的活动

  LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  LocationListener mlocListener = new MyLocationListener();
  mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

你的听众班

@Override
      public void onLocationChanged(Location loc){
       //you are getting values
        loc.getLatitude();
        loc.getLongitude();
      }

清单许可

    <uses-permission android:name="android.permission.ACCESS_GPS"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2012-09-12T07:11:13.347 回答