【发布时间】:2014-05-08 12:46:33
【问题描述】:
我有一个AsyncTask class,它将执行HttpGet-request。我想在 AsyncTask 完成后做点什么,但在我的 MainActivity 内。
这是我的TaskGetAPI class:
public class TaskGetAPI extends AsyncTask<String, Void, String>
{
private TextView output;
private Controller controller;
public TaskGetAPI(TextView output){
this.output = output;
}
@Override
protected String doInBackground(String... urls){
String response = "";
for(String url : urls){
HttpGet get = new HttpGet(url);
try{
// Send the GET-request
HttpResponse execute = MainActivity.HttpClient.execute(get);
// Get the response of the GET-request
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while((s = buffer.readLine()) != null)
response += s;
content.close();
buffer.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String result){
if(!Config.LOCALHOST)
output.setText(result);
else
controller = Controller.fromJson(result);
}
public Controller getController(){
return controller;
}
这是我的 MainActivity 中我使用此类的方法:
private void sendGetRequest(){
...
// Web API GET-request
if(!get_url.equals("") && get_url != null){
TaskGetAPI task = new TaskGetAPI(output);
task.execute(new String[] { get_url });
// TODO: When AsyncTask is done, do:
controller = task.getController();
Log.i("CONTROLLER", controller.toString());
}
}
如您所见,我在AsyncTask 的onPostExecute-method 中设置了稍后使用的Controller。
由于这与Async tasks 的全部目的背道而驰,我首先想到删除extends AsyncTask 并只为我的HttpGet 创建一个常规类和方法,但后来我得到一个android.os.NetworkOnMainThreadException,这意味着我需要使用一个AsyncTask(或类似的东西)在与我的MainThread不同的thread中使用HttpGet。
那么,有人知道我应该在// TODO 上放什么吗?
我确实尝试使用getter 将boolean field (isDone) 添加到TaskGetAPI 类,然后使用:
while(true){
if(task.isDone()){
Controller controller = task.getController();
Log.i("CONTROLLER", controller.toString());
}
}
但随后会发生以下步骤:
-
TaskGetAPI类的doInBackground已经完成。 - 现在我们被困在这个
while(true)-loop..
并且永远不会调用将isDone 设置为true 的onPostExecute。
【问题讨论】:
标签: android http asp.net-web-api android-asynctask get