My current location always returns null. How can I

2020-01-25 00:22发布

问题:

I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do I always get a null value?

locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          
Criteria crit = new Criteria();     
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);    

if (location != null) {                 
    System.out.println("Location is not null!");
    lat = (int) (location.getLatitude() *1E6);
    longi = (int) (location.getLongitude() * 1E6);
    GeoPoint ourLocation = new GeoPoint(lati, longi);
    OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
                                                            "2nd String");
    CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
    custom.insertPinpoint(overlayItem);
    overlayList.add(custom);
    overlayList.clear();
} else {
   System.out.println("Location is null! " + towers);
   Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
                                                                    .show();
}

回答1:

getLastKnownLocation() uses the location(s) previously found by other applications. if no application has done this, then getLastKnownLocation() will return null.

one thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. for example,

private Location getLastKnownLocation() {
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        ALog.d("last known location, provider: %s, location: %s", provider,
                l);

        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            ALog.d("found best last known location: %s", l);
            bestLocation = l;
        }
    }
    if (bestLocation == null) {
        return null;
    }
    return bestLocation;
}

if your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. you can take a look at this class for an example,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

see the method onStartCommand(), where it checks if the network provider is enabled. if not, it uses last known location. if it is enabled, it registers to receive location updates.



回答2:

if u find current location of devices the use following method in main class

public void find_Location(Context con) {
    Log.d("Find Location", "in find_location");
    this.con = con;
    String location_context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) con.getSystemService(location_context);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 1000, 0,
            new LocationListener() {

                public void onLocationChanged(Location location) {}

                public void onProviderDisabled(String provider) {}

                public void onProviderEnabled(String provider) {}

                public void onStatusChanged(String provider, int status,
                        Bundle extras) {}
            });
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            addr = ConvertPointToLocation(latitude, longitude);
            String temp_c = SendToUrl(addr);
        }
    }
}

And Add User Permission method in your manifest file

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


回答3:

Try this this will not give you null current location

class GetLastLocation extends TimerTask {

    LocationManager mlocManager = (LocationManager) 
            getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListenerTmp = new CustomLocationListener();
    private final Handler mLocHandler;

    public GetLastLocation(Handler mLocHandler) {
        this.mLocHandler = mLocHandler;
    }

    @Override
    public void run() {
        timer.cancel();
        mlocManager.removeUpdates(mlocListenerTmp);
        Location location = mlocManager
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        {
            if (mlocListenerTmp != null) {
                mlocManager.removeUpdates(mlocListenerTmp);
            }
            currentLocation = location;
        }
        if (location != null) {
            String message = String.format(
                "Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());
            Log.d("loc", " :" + message);
            Bundle b = new Bundle();
            {
                b.putBoolean("locationRetrieved", true);
                {
                    Message msg = Message.obtain();
                    {
                        msg.setData(b);
                        mLocHandler.sendMessage(msg);
                    }
                }
            }
        } else {
            Log.d(
                "loc",
                ":No GPS or network signal please fill the location manually!");
            location = mlocManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                currentLocation = location;
                Bundle b = new Bundle();
                {
                    b.putBoolean("locationRetrieved", true);
                    {
                        Message msg = Message.obtain();
                        {
                            msg.setData(b);
                            mLocHandler.sendMessage(msg);
                        }
                    }
                }
            } else {
                Bundle b = new Bundle();
                {
                    b.putBoolean("locationRetrieved", false);
                    {
                        Message msg = Message.obtain();
                        {
                            msg.setData(b);
                            mLocHandler.sendMessage(msg);
                        }
                    }
                }
            }
        }
    }
}

call it like this

timer.schedule(new GetLastLocation(mLocHandler), 3000);

and the customLocationclass is as follows

public class CustomLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        loc.getLatitude();
        loc.getLongitude();
        currentLocation = loc;
        String Text = "My current location is: " + "Latitud = "
            + loc.getLatitude() + "Longitud = " + loc.getLongitude();
        Log.d("loc", "onLocationChanged" + Text);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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


回答4:

If you are trying it out in a marshmallow device, try enabling location permission for your app manually.



回答5:

turn on your GPS by using below method. it helps you to show your current location without any ERROR. call it in onCreate

public void displayLocationSettingsRequest(Context context, int requestCode) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(result1 -> {
        final Status status = result1.getStatus();
        if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
            try {
                status.startResolutionForResult((Activity) context, requestCode);
            } catch (IntentSender.SendIntentException ignored) {
            }
    });


回答6:

If you are getting a null error with your provider list, change...

List<String> providers = mLocationManager.getProviders(true);

to...

List<String> providers = locationManager.getAllProviders();

This worked for me, and make sure that you have the following in your AndroidManifest.xml file...

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


回答7:

Have you tried reversing the code? For example, if(location==null) then print that location is null, and else print location is not null. I got that problem once before and that seemed to have fixed it (i don't know why). Try that.

If that doesn't work, perhaps the google maps API is returning the null value, in which case its a problem with the GM-API or with the call method. Any of these could be the problem.

Hope this helps,

-JXP