在Oreo及以上没有调用LocationListener.onLocationChanged

时间:2018-06-19 06:36:35

标签: java android location android-8.0-oreo

我在代码下方使用以获取当前位置:

private void getCurrentLocation() {
    LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.i(TAG, "Location: " + location.getLatitude() + ", " + location.getLongitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    String locationProvide = LocationManager.NETWORK_PROVIDER;
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    locationManager.requestLocationUpdates(locationProvide, 0, 0, locationListener);
    Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (lastLocation != null) {
        Log.i(TAG, "Last Location: " + lastLocation.getLatitude() + ", " + lastLocation.getLongitude());
    }
}
AndroidManifest中的

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

这适用于8岁以下的Android,但是从未调用过8.1 onLocationChanged。我找到了这个link,它说必须由类实现LocationListener。但它也无济于事。

也许我错过了一些东西或Google为oreo提供了另一种定位方法?我很感激你的帮助。感谢

0 个答案:

没有答案