代码之家  ›  专栏  ›  技术社区  ›  Paul

Android java AsyncTask wait onPostExecute返回方法

  •  -1
  • Paul  · 技术社区  · 7 年前

    问题是异步操作,当我这样做的时候 html.getTi() ,没有给我任何值,因为操作仍在运行,而且我速度更快。

    我试着用: synchronized (this) {.. 但它似乎不起作用。

    我考虑过使用等待循环:

    while(html.getFlg ()! = false);

    我想用 callbacks promises

    一些建议?

    主类

    Html html = new Html().execute("...");
    html.getTi();//return element ArrayList<ListItem>
    

    Html.java文件

    public class Html extends Activity {
    
        ArrayList<ListItem> listItemList = new ArrayList<ListItem>();
    
        public Html execute(String str) {
            new Http().execute(str);
            return this;
        }
    
        public ArrayList<ListItem> getTi() {
            return listItemList;
        }
    
        public class Http extends AsyncTask<String, Void, Void> {
            @Override
            protected void onPreExecute() { super.onPreExecute(); }
    
            @Override
            protected Void doInBackground(String... params) {
    ...
            }
    
            @Override
            protected void onPostExecute(Void result) {
    ...
            }
    
        }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Onix    7 年前

    你可以简单地使用图书馆 okHttp

    OkHttpClient client = new OkHttpClient();
    
    Request request = new Request.Builder()
                         .url(YOUR_URL)
                         .build();
    
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    
        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            } else {
            // do something wih the result
        }
    }
    
    推荐文章