getLastKnownLocation方法始终返回null方法、getLastKnownLocation、null

2023-09-12 08:06:57 作者:回忆再美丶终究是回忆

我有一个问题,以固定的位置。我用 getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 但总是返回null,我在设置权限的的Andr​​oidManifest.xml

I have a problem to fixed position. I use getLastKnownLocation(LocationManager.NETWORK_PROVIDER); but always return null, i have set the permissions in your AndroidManifest.xml.

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

在设置中启用 - >位置与安全 - >通过网络位置

and enabled in Settings --> Location and Security --> location through network.

TextView locationShow = (TextView) this.findViewById(R.id.location);
    double latitude = 0.0, longitude = 0.0;
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }
    else {
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                if (location != null) {
                    Log.i("SuperMap", "Location changed : Lat: " + location.getLatitude() + " Lng: " +
                        location.getLongitude());
                }
            }

            public void onProviderDisabled(String provider) {
            }

            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        };
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                                               locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
        locationShow.setText("经度:" + latitude + "纬度:" + longitude);

我发现其他应用程序可以正确显示的位置,所以也许有什么错我的code。

I find that other apps can show the location correctly, so maybe there something wrong with my code.

推荐答案

getLastKnownLocation()给最后一个有效的缓存位置。

getLastKnownLocation() give the last valid cached location.

正在试图从网络提供的高速缓存位置。你必须等待几分钟,直到你得到有效的修复。由于网络提供的高速缓存是空的,你显然得到一个有。

You are trying to get the cached location from the Network Provider. You have to wait for a few minutes till you get a valid fix. Since the Network Provider's cache is empty, you are obviously getting a null there.

 
精彩推荐
图片推荐