В зависимости от используемой версии android может потребоваться также использовать ACCESS_COARSE_LOCATION. Попробуйте добавить его в манифест и запросить разрешение в вашей активности.
Однажды я написал рабочий класс для постоянного отслеживания местоположения устройств.
private static LocationManager locationManager=null;
private static LocationListener locationListener=null;
public static void startTrackingLocation(final Context context, final LocationChangedListener listener) {
startTrackingLocation(context, listener, 0.5, 1);
}
/**
* Location gets requested periodically, and a call on abstract listener.onLocationChanged(Location l)
* is performed if distance between locations is > distance
* @param context context to gather the location from
* @param listener listens to location changes
* @param minutes interval between the location requests
* @param distance minimal distance to trigger onLocationChanged(Location l)
*/
public static void startTrackingLocation(@NotNull final Context context, @NotNull final LocationChangedListener listener, final double minutes, final int distance) {
initLocationManager(context);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
listener.onLocationChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
};
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, (int)(minutes*60000), distance, locationListener);
} catch (SecurityException ignored) { }
}
private static void initLocationManager(@NotNull final Context context) {
if (null==locationManager) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
}
@SuppressWarnings("unused")
public static void stopTrackingLocation() {
if (null!=locationManager && null!=locationListener) {
locationManager.removeUpdates(locationListener);
}
}
public static Location getLocation(final Context context) {
initLocationManager(context);
Location locationGPS=null, locationNet=null;
try {
locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (SecurityException ignored) { }
if (null != locationNet) {
return locationNet;
}
return locationGPS;
}
@SuppressWarnings("unused")
private static double distance(final double lat1, final double lon1, final double lat2, final double lon2) {
final double theta = lon1 - lon2;
double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
dist = Math.toDegrees(Math.acos(dist)) * 60 * 1850 ; // 1 degree is 111km 111/60=1.85
return (dist);
}
Класс LocationChangedListener - это абстрактный класс I написал, чтобы поймать событие, где место было изменено.
Код очень прост:
public abstract void onLocationChanged(Location location);
В вашей деятельности:
LocationChangedListener listener = new LocationChangedListener() {
@Override
public void onLocationChanged(Location location) {
MainActivity.this.onLocationChanged(location);
}
};
Это полностью работает на моем android устройство, вы можете попробовать. Кроме того, функция Location getLocation (конечный контекстный контекст) может быть опущена, поскольку она дает вам только местоположение устройств в данный момент времени.
Я использовал те же разрешения в манифесте. Это также должно работать для вас.