LocationManager don't get the right results

2020-02-16 02:16发布

问题:

I am using LocationManager to convert from lat,longi to get the city name, but I am getting wrong results, I think there is something wrong in this code here:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
          System.out.println("Provider " + provider + " has been selected.");
          onLocationChanged(location);
          Log.d("msgh","msgh");
        } else {
             System.out.println("location not available");
            Log.d("msg","msg");
        }

the code doesn't enter the if statement and always enters the else statement.

after Editing, this is the logCat:

11-24 15:06:25.072: E/AndroidRuntime(6963): FATAL EXCEPTION: main
11-24 15:06:25.072: E/AndroidRuntime(6963): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.survivingwithandroid.weatherapp/com.survivingwithandroid.weatherapp.MainActivity}: java.lang.NullPointerException
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.os.Looper.loop(Looper.java:137)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at java.lang.reflect.Method.invoke(Method.java:525)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at dalvik.system.NativeStart.main(Native Method)
11-24 15:06:25.072: E/AndroidRuntime(6963): Caused by: java.lang.NullPointerException
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.location.GeocoderParams.<init>(GeocoderParams.java:50)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.location.Geocoder.<init>(Geocoder.java:83)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at com.survivingwithandroid.weatherapp.MainActivity.onCreate(MainActivity.java:227)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.Activity.performCreate(Activity.java:5133)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-24 15:06:25.072: E/AndroidRuntime(6963):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

回答1:

Did you try turning on your gps to get a location fix? According to the docs, this method returns:

the last known location for the provider, or null

Make sure you had a location fix on your phone before for this to work. Also, you might want to consider this post which covers a good strategy to get the user location when there is one available or request a new one otherwise.

Hope it helps.



回答2:

Here is the full code of getting location. This code will automatically give you the best provider available(GPS or Network). Moreover, it won't give you the last known location but the current location.

protected String currentLatitude, currentLongitude;
double lat, lon;
protected LocationManager locationManager;
private LocationListener ll;
locationManager = (LocationManager) getSystemService(
            Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            Toast.makeText(this,
                    "GPS enabled. Finding fine location. ",
                    Toast.LENGTH_SHORT).show();
        ll = new GpsListener();
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 0, 0, ll);

    } else {
        if (locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

                Toast.makeText(this,
                        "GPS disabled. Finding coarse location.",
                        Toast.LENGTH_SHORT).show();
            ll = new GpsListener();
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, 0, 0, ll);

        } else {
            Toast.makeText(this,
                    "Enable location settings to get current location.",
                    Toast.LENGTH_LONG).show();

        }
    }

private class GpsListener implements LocationListener {

    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null) {
            try {
                Toast.makeText(getApplicationContext(), "Location Found",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {

            }

            lat = location.getLatitude();
            lon = location.getLongitude();
                            Geocoder gcd = new Geocoder(context, Locale.getDefault());
                            try{
                            List<Address> addresses = gcd.getFromLocation(lat, lon, 1);
                            if (addresses.size() > 0) 
                            String cityName=addresses.get(0).getLocality();
                            }
                             catch (IOException e) {}
                             catch (NullPointerException e) {}
            currentLatitude = Double.toString(lat);
            currentLongitude = Double.toString(lon);
            try {
                if (ll != null)
                    locationManager.removeUpdates(ll);
            } catch (Exception e) {

            }

            locationManager = null;

        } else {
            Toast.makeText(getApplicationContext(), "No Location Found",
                    Toast.LENGTH_LONG).show();

        }

    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}// end of Class

Edit- Be sure to have the following permissions in your Android Manifest:

android.permission.INTERNET

android.permission.ACCESS_NETWORK_STATE

android.permission.ACCESS_COARSE_LOCATION

android.permission.ACCESS_FINE_LOCATION