Android AsyncHttpClient调用等待完成

时间:2015-10-03 14:51:17

标签: java android multithreading user-interface http

在我的Android应用程序中,我有时会进行同步HTTP调用。由于这不可能来自主UI线程,我试图通过使用com.loopj.android.http.AsyncHttpClient和处理程序来规避问题。在我的代码中,我尝试等待完成的调用:

public class someclass {
...
//asynchronous HTTP handler for Android
private static AsyncHttpClient httpClient = new AsyncHttpClient(); 
...
public void somemethod() {
...
httpClient.get(request, handler);
    ...
    //waiting for call to be finished
    do {
        Thread.sleep(100); //for testing only
        log.info("sleeping...");
    } while (!handler.isFinished());


    response = handler.getBody();
    log.info("Async resp = " + response);
 ...

我编写了自己的处理程序类:

    public class MyAsyncHTTPResponseHandler extends AsyncHttpResponseHandler {



    private String header = null;
    private String body = null;
    private int status = 0;
    boolean finish = false;

    public MyAsyncHTTPResponseHandler() {
        super();
        log.info("init Http handler ");
        finish = false;
    }

    @Override
    public void onStart() {
        // called before request is started
        log.info("starting Async Get");
        finish = false;
    }

    @Override
    public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {


        body = new String(responseBody);
        status = statusCode;
        finish = true;

        log.info("Async Get worked fine " + responseBody);
    }



    @Override
    public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, java.lang.Throwable error) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        log.info("Error in executing URL get " + statusCode + " " + responseBody);
        finish = true;
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
    }

    public String getBody() {
        return body;
    }

    public int getStatusCode() {
        return status;
    }

    public boolean isFinished() {
        return finish;
    }

}

不幸的是,这不起作用。将执行onStart()方法,但循环将永远运行。不会调用onSuccess()方法。

如果我注释掉循环,身体反应将为空。正如我在日志中看到的那样,在onSuccess()中我的日志语句之后将调用somemethod()方法。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是将volatile关键字添加到变量finish。 或者使用同步:

public synchronized void setFinish()
   {
       finish = True;
   }

   public synchronized boolean isFinished()
   {
       return finish;
   }