How to get last known location for Location manager in Android?

后端 未结 7 1382
-上瘾入骨i
-上瘾入骨i 2021-01-11 10:34

I am using simple location manager object to get lastKnownLocation() of device but getting null object in

相关标签:
7条回答
  • 2021-01-11 11:07

    Best method I have found:

    private Location getLastKnownLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    
        List<String> providers = locationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = locationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location:
                bestLocation = l;
            }
        }
    
        return bestLocation;
    }
    

    The locationManager variable you can get from the system service LOCATION.

    0 讨论(0)
提交回复
热议问题