public class LocationUtils {
private static final long LOCATION_REFRESH_TIME = 5000L;
private static final float LOCATION_REFRESH_DISTANCE = 300;
LocationListener mLocationListener;
public void fetchLocation(Context context, LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
try {
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
@SuppressLint("MissingPermission")
Location location = locationManager.getLastKnownLocation(provider);
if (callback != null && location != null) {
String locationString = getLocationString(location);
Timber.i("LocationUtils = " + locationString);
callback.onLocationLocked(locationString);
removeListener(locationManager);
return;
}
if (mLocationListener == null) {
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
removeListener(locationManager);
if (callback != null) {
String locationString = getLocationString(location);
if (locationString != null) {
Timber.i("LocationUtils = " + locationString);
callback.onLocationLocked(locationString);
} else {
callback.onLocationLockFailed(new LocationNotFoundException());
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(provider, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
} catch (Exception e) {
removeListener(locationManager);
if (callback != null) {
callback.onLocationLockFailed(e);
}
}
}
private void removeListener(LocationManager locationManager){
try {
locationManager.removeUpdates(mLocationListener);
}catch (Exception e){
}
mLocationListener = null;
}
private String getLocationString(Location location) {
if (location != null) {
return location.getLatitude() + "," + location.getLongitude();
}
return null;
}
public interface LocationCallback {
void onLocationLocked(String location);
void onLocationLockFailed(Exception e);
}
public class LocationNotFoundException extends Exception {
}
}
This is my code i want to get one more method time out exception so that if Location Service will not able to fetch location then that timeout exception should be invoked and accordingly we can handle it but there is not overrides method for timeout in location service please suggest me how we will implement this using time or timer class in android