简体   繁体   中英

onClick get GPS location

I want to get current GPS location when button is clicked. I have written this code (given below) but this gives NullPointerException for location object that is Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); . please tell what is problem with my code?

Code:

@Override
public void onClick(View v) {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    }
    String cur_loc = "latitude = " + location.getLatitude() + "\n" + location.getLongitude(); //this is line 54 in my code
    Toast.makeText(ctx, cur_loc, Toast.LENGTH_LONG).show();
}

AndroidManifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

getLastKnownLocation (String provider) may well return null. see Documentation :

Returns a Location indicating the data from the last known location fix obtained from the given provider.

This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

If the provider is currently disabled, null is returned.

try this method:

    private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}

Now use it as:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation = getLastKnownLocation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM