我有這樣的代碼:我需要一些幫助等待的線程結束
jsonObject1=getLocationInfo(direction);
它的目的是返回一個JSONObject,以後將被解析,我會得到lattitude和經度。
這是方法:
public JSONObject getLocationInfo(final String address) {
Thread thread=new Thread(){
public void run(){
String adressString=address.replaceAll("\\s+",",");
StringBuilder stringBuilder = new StringBuilder();
try {
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + adressString + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
;
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
return jsonObject;
}
問題是...因爲這方法涉及HTTPGET,它必須在另一個線程。但是,在thread.start()方法之後,返回的jsonObject行被調用,所以返回的對象將爲空......我怎麼能等待線程在返回之前結束?
謝謝。
使用asynctask它更容易編碼。 – Raghunandan
如果您在開始/等待某個線程後不做任何操作,則不需要/不應該使用線程。你不會得到'NetworkOnMainThreadException',因爲你隱藏了阻止http的主線程的事實,但你基本上是在主線程中執行它,因爲只要另一個線程執行http,它就會等待。 – zapl