我有一个函数,它将url请求发送到服务器并获取数据。我能够获取数据,但由于请求是在另一个线程中发送的,因此数据迟到了。
我希望用户等待请求(用于登录身份验证)。怎么做到这一点?
private String sendRequest(final String URL) {
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
HttpURLConnection httpUrlConnection = null;
try {
httpUrlConnection = (HttpURLConnection) new URL(URL)
.openConnection();
InputStream in = new BufferedInputStream(
httpUrlConnection.getInputStream());
data = readStream(in);
Log.i(TAG,"Respose from "+URL);
System.out.println(data);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} finally {
if (null != httpUrlConnection)
httpUrlConnection.disconnect();
}
}
}).start();
return data;
}
我在上面调用了这个函数
public JSONObject get(String URL){
data = sendRequest(URL);
try {
if(null!=data){
returnJsonObj = new JSONObject(data);
}else{
Log.i(TAG,"Response data is null");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnJsonObj;
}
如何在获取功能中等待数据。