Recently, I created a simple application to get the GPS location and display it on an Android phone. In the beginning I was able to get the location after a few tries. But, after I reinstalled the APK file, the getLastKnownLocation() always returns a null value.

The development environment:

  • API 10 Gingerbread 2.3.6
  • GPS provider is used

Below is the code I applied to my Android project:

public class MyActivity extends MapActivity {

  protected void onCreate(Bundle savedInstanceState) {

    mapView = (MapView) findViewById(R.id.myTripMap);
    mapController = mapView.getController();
    mapView.setSatellite(false);
    mapView.setStreetView(true);
    mapView.displayZoomControls(false);
    mapView.setBuiltInZoomControls(true);//
    mapView.setClickable(true);
    mapController.setZoom(14);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    provider = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(provider);

    updateMyCurrentLoc(location);

    locationManager.requestLocationUpdates(provider, 2, 1, locationListener);
  }

  private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateMyCurrentLoc(location);
    }

    public void onProviderDisabled(String provider) {
      updateMyCurrentLoc(null);
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status,
        Bundle extras) {
    }
  };

  private void updateMyCurrentLoc(Location location) {

    if (location != null) {

      // other codes to get the address and display
      Toast.makeText(getBaseContext(), 
Edit
Report