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 {
}
}
这是我的代码,我想再获取一个方法超时异常,以便如果位置服务无法获取位置,则应调用该超时异常,因此我们可以处理该异常,但在其中没有覆盖超时的方法定位服务,请建议我如何使用android中的time或timer类实现此功能
答案 0 :(得分:0)
请尝试按照以下说明对您有帮助
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
// ....show message
break;
case LocationProvider.OUT_OF_SERVICE:
// ...show message
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
// ...show message
break;
}
}
并相应显示消息
答案 1 :(得分:0)
Ganesh给出的答案看起来不错,并且是预期的实现方式,但是,如果您要配置自己的超时时间,也许可以对以下问题使用以下答案:How to timeout a thread
因此,您创建了一个独立的线程来调用获取位置,并且如果超时到期,您可以做任何您想做的事情(可能还需要删除侦听器)