English 中文(简体)
getlastknownlocation always return null after I re-install the apk file via eclipse
原标题:

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(), "provider used : " + provider).show();  //testing purpose
    } else {
      str = "No location found";
      Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
    }
  }
}

Can anyone suggest a possible solution to solve the null value returned by getLastKnownLocation()?

问题回答

Try Following Code

LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    Location lastlocation = locationManager.getLastKnownLocation(locationProvider);

    String CurLat = String.valueOf(lastlocation.getLatitude());
    String Curlongi= String.valueOf(lastlocation.getLongitude());

This solution is my little improvement for code by Ravi Tamada.

    public Location getLocation() {
    int MIN_TIME_BW_UPDATES = 10000;
    int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10000;
    try {
        locationManager = (LocationManager) getApplicationContext()
                .getSystemService(LOCATION_SERVICE);

        boolean isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        boolean isPassiveEnabled = locationManager
                .isProviderEnabled(LocationManager.PASSIVE_PROVIDER);

        boolean isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isGPSEnabled || isNetworkEnabled || isPassiveEnabled) {

            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled && location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
            }
            if (isPassiveEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.PASSIVE_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                }
            }

            if (isNetworkEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }

        }else{
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

You just need to add one more line into the code

if (locationManager != null) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

    } else {
        Toast.makeText(
                mContext,
                "Location Null", Toast.LENGTH_SHORT).show();
    }
}

I got the same issue after re-install via eclipse. I solved going to Android settings / Security / app permissions and confirm location permissions to the application.





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签