0

我希望有人可以对此有所了解。我试图弄清楚为什么我的 2.2 代码突然不能与 2.3 一起使用。我有点疑惑。这是一直在工作的代码,但现在正在引发空指针异常。

@Override
public void onStart(Intent intent, int startId) {
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location l){
        Log.i("MYSERVICE", "LocationChanged " + l);
        }
        public void onStatusChanged(String provider, int status, Bundle Extras) {}
        public void onProviderEnabled(String provider){
        Log.i("MYSERVICE", "ProviderEnabled " + provider);
        }
        public void onProviderDisabled(String provider) {}
        };

        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    super.onStart(intent, startId);
    String location = getLocation();
}


public String getLocation() {
    String provider = LocationManager.GPS_PROVIDER;
    Location location = lm.getLastKnownLocation(provider);
    Double lat = location.getLatitude();
    Log.i("lat", lat.toString());
    double lng = location.getLongitude();
    String writeString = lat+"&"+lng;
    return writeString;
}

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

我也在使用 2.3 模拟器。任何帮助将不胜感激,干杯!

4

2 回答 2

1

getLastKnownLocation如果没有先前的位置,则可以返回 null。如果是这样,您需要等待onLocationChanged您注册的侦听器中的值。

于 2011-03-17T02:12:13.537 回答
-1

似乎 android 2.3 不适用于“0,0”lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

您需要将这 2 个参数设置为至少 1 和 1: lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);

于 2012-03-29T12:57:25.920 回答