Android geolocation works in 2.2, but not 2.3
I was hoping someone could shed some light on this. I'm trying to figure out why all of a sudden my code from 2.2 will not work with 2.3. I'm a little bit puzzled. This is the code that has been w开发者_StackOverfloworking, but is now throwing a null pointer exception.
@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"/>
I am using a 2.3 emulator as well. Any help would be greatly appreciated, cheers!
getLastKnownLocation
can return null if there is no previous location. If so, you need to wait for the value in onLocationChanged
with the listener you registered.
It seems that android 2.3 does not work with "0,0" on lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
You need to set those 2 parameters to at least 1 and 1:
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);
精彩评论