protected void showCurrentLocation(){
Location lc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(lc != null){
String msg = String.format("Current Location \n Logitude: %1$s \n Latitude: %2$s",lc.getLongitude(),lc.getLatitude());
Toast.makeText(Test1.this,msg,3000).show();
}
Toast.makeText(Test1.this,"location is null",3000).show();
}
from code above, when I run on an Android phone, it can run but it only shows location as null. I don't know why it can't get location from getLastKnownLocation()
http://www.ja开发者_JAVA技巧vacodegeeks.com/2010/09/android-location-based-services.html
This is source code which I got to try. Please help me. Thanks ka :))
Ps. I already have ACCESS_FINE_LOCATION,ACCESS_MOCK_LOCATION, and ACCESS_COARSE_LOCATION
Do your application have permissions for using GPS?
http://developer.android.com/reference/android/Manifest.permission.html
P.S: Here (http://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-returns-null) is suggested the following - to use LocationListener
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//TODO:enter your code here
}
}
Also you can use LocationOverlay:
final MyLocationOverlay overlay = new MyLocationOverlay(this, mapView);
overlay.enableMyLocation();
overlay.runOnFirstFix(new Runnable() {
public void run() {
//TODO: update some model, etc
}
});
Daisy, I think what you are struggling with is the concept of getLastKnownLocation(). In the emulator, you manually send the mock location and there is indeed a last known location when you run your code. On your actual phone, there may not be a last known location, yet...
You're probably thinking "But doesnt my phone always know its location" and the answer is maybe but not always.
So as mentioned above, you really need to write your code to listen for location updates from a location manager
精彩评论