How to acquire a user's GPS location on an Android (2.2) device
I am attempting to simply acquire the user's GPS location, but my application crashes when trying to get the latitude and longitude of the device. See code for where the error occurs..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation开发者_如何学Go(LocationManager.GPS_PROVIDER);
final double longitude = location.getLongitude(); //error occurs here
final double latitude = location.getLatitude(); //and here
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
//longitude = location.getLongitude();
//latitude = location.getLatitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//update location via GPS PROVIDER
//can also use LocationManager.NETWORK_PROVIDER
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
I am also including the ACCESS_FINE_LOCATION permission in the manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
so I'm not quite sure why this does not work. Any help would be greatly appreciated!
I think you can check this StackOverflow Question: What is the simplest and most robust way to get the user's current location on Android?
Your error is most probably at: lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
It is because the getLastKnownLocation is a non blocking call and assuming the application has just started there is no 'last known location' that the system has. You might want to loop till you dont get a non-null value for getLastKnownLocation.
精彩评论