How to Obtain Current Location in Android
Understanding the Issue
You are experiencing difficulties obtaining current location coordinates using Android's NETWORK location provider. Despite implementing multiple existing classes, you consistently receive outdated coordinates.
Implementation Details
Define a LocationListener to handle location updates:
private final LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(final Location location) { // Custom code for handling location changes } };
Obtain the LocationManager and request location updates:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, mLocationListener); }
Constants for location refresh time and distance:
int LOCATION_REFRESH_TIME = 15000; // 15 seconds to update int LOCATION_REFRESH_DISTANCE = 500; // 500 meters to update
For network-based location:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS-based location:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
The above is the detailed content of Why Are My Android Location Updates Outdated Using the NETWORK Provider?. For more information, please follow other related articles on the PHP Chinese website!