Android的网络访问由于不容许运行在主线程,所以一般的网络相关方法都是异步调用的,但有时候有需要获得根据网络方法返回的结果,这时候就需要将异步方法转为同步。直接用wait notify就可以:
public synchronized NaviLatLng searchLocation(Context context, String address, String city) {
GeocodeSearch geocodeSearch = new GeocodeSearch(context);
geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
//todo
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int rCode) {
if(rCode == 1000) {
if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
geocodeResult.getGeocodeAddressList().size() > 0) {
GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
double latitude = geocodeAddress.getLatLonPoint().getLatitude();
double longitude = geocodeAddress.getLatLonPoint().getLongitude();
mNavi = new NaviLatLng(latitude, longitude);
}
}
finished = true;
synchronized (lock) {
lock.notifyAll();
}
}
});
finished = false;
mNavi = null;
GeocodeQuery query = new GeocodeQuery(address, city);
geocodeSearch.getFromLocationNameAsyn(query);
synchronized (lock) {
try {
if(!finished) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return mNavi;
}

本文介绍了一种在Android中将异步网络请求转换为同步请求的方法,通过使用wait和notify机制,实现在主线程中等待网络请求结果返回,解决了无法在主线程中直接获取网络请求结果的问题。
2488

被折叠的 条评论
为什么被折叠?



