Android Get latitude and longitude with location m

2019-03-04 15:47发布

I'm trying to get the user location with location manager but the location always returns null. I also am asking to the user to turn on the gps.

This is my code:

   int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);

    if(permisioncheck == 0){

        lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);

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

        Location bestLocation = null;

        for (String provider : providers) {
            Location location = lm.getLastKnownLocation(provider);
            if (location == null) {
                continue;
            }

            if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = location;
            }
        }

        if(bestLocation == null){
            System.out.println("is NULL!");
        }
    }else{

        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }

I hope that someone could help me to find the error, thanks.

1条回答
Lonely孤独者°
2楼-- · 2019-03-04 15:58

The "error" is that you are assuming that getLastKnownLocation() will return a Location. Frequently, it will return null. Use getLastKnownLocation() as a possible optimization, but otherwise you need to requestLocationUpdates(), then use the location in the onLocationChanged() method.

See this sample project and the documentation for more.

查看更多
登录 后发表回答