在AsyncTask中等待回调

时间:2015-11-06 10:57:05

标签: android android-asynctask okhttp

我想在AsyncTask中做一些工作,包括下载小文件的一些服务器请求。下载完成后继续AsyncTask内的逻辑,当所有内容完成后,我将结果显示在活动中。一切都很好但我的AsyncTask并没有等待回调方法:

public class AsyncOperation extends AsyncTask<String, Integer, String> {

@Override
protected String doInBackground(String... params) {
    String linkUrl = params[0];

    functionDoStuff(linkUrl);

    return "Executed";
}

public void functionDoStuff(String urlLink) {

    ... code ...

    String str = getFile(urlLink);

    !!! is not waiting for result !!!

    ... use 'str' ...

}

private String getFile(String urlLink) {
    String savedFileDestination = null;

    OkHttpClient client = new OkHttpClient();
    final Request request = new Request.Builder()
            .url(urlLink")
                    .build();

    client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            //something goes wrong
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {

            //get stream
            InputStream inputStream = response.body().byteStream();

            //this method save file and return file path
            savedFileDestination = saveFileMethod(inputStream);
        }
    });

        return savedFileDestination;
    }

}

如何等待此回调继续functiobDoStuff()中的逻辑?

2 个答案:

答案 0 :(得分:0)

将所有内容放在onResponse方法中。因为onResponse方法工作asyncronusly

答案 1 :(得分:0)

@Selvin是对的,我必须提出同步,我的'等待问题'已经消失了!

唯一的变化是getFile()方法,它应该像:

   private void getFile(String urlLink) {
    OkHttpClient client = new OkHttpClient();

    final Request request = new Request.Builder()
            .url(urlLink)
            .build();

    try {
        Response response = client.newCall(request).execute();
        if (response!=null){
            InputStream inputStream = response.body().byteStream();
            saveFile(inputStream);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}