The getLastKnownLocation method always returns null

I have a problem with a fixed position. I am using getLastKnownLocation(LocationManager.NETWORK_PROVIDER); but always return null, I set permissions in AndroidManifest.xml .

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

and is included in the settings β†’ Location and Security β†’ location through the 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); 

I found that other applications can correctly show the location, so maybe something is wrong with my code.

+4
source share
1 answer

getLastKnownLocation() specify the last valid cache location.

You are trying to get a cached location from a network provider. You have to wait a few minutes until you get the right solution. Since the network provider's cache is empty, you obviously get null .

+3
source

All Articles