【问题标题】:Async in a Async task异步任务中的异步
【发布时间】:2013-12-04 10:22:04
【问题描述】:

我将以下代码放在另一个AsyncTask 中的doInBackground() 中,这个HttpPostHandler 包含另一个AsyncTask。然后handler.get() 继续加载。
有人对此有任何想法吗?
这是线程的问题吗???

代码:

@Override
    protected Void doInBackground(Void... params) {
        try {
                champ = Utility.getCounter("test");

                this.wait(3);
                }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

在实用程序中:

public static int getCounter(String code) {
    HttpPostHandler handler = new HttpPostHandler();
    try {
        handler.execute(counter_URL + code);
        handler.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    String html = handler.getResultJSONString();
    TagNode tagNode;

    ...
}

以下是HttpPostHandler AsyncTask

    public class HttpPostHandler extends AsyncTask<String, Void, String> {

        private String url;
        private String resultJSONString=null;
        private JSONObject resultJSON;

        public String getResultJSONString() {
            return resultJSONString;
        }

        public void setResultJSONString(String resultJSONString) {
            this.resultJSONString = resultJSONString;
        }

        private static String toUTF8(InputStream is){
            //InputStream is = resEntity.getContent();
            InputStreamReader isr = null;
            StringBuffer buffer = new StringBuffer();
            try {
                isr = new InputStreamReader(is, "utf-8");
                Reader in = new BufferedReader(isr);
                int ch;
                while((ch = in.read()) != -1){
                    buffer.append((char)ch);
                }
                isr.close();
                is.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e){
                e.printStackTrace();
            }
            return buffer.toString();
        }

        @Override
        protected String doInBackground(String... params) {
                String result = "";
                DefaultHttpClient client = new DefaultHttpClient();
                try {
                    HttpGet get = new HttpGet(params[0]);
                    HttpResponse response = client.execute(get); 
                    Log.d("danny", "response = "+response);
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = toUTF8(resEntity.getContent());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    client.getConnectionManager().shutdown();
                }
                setResultJSONString(result);
                return result;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            resultJSONString = result;
        }
    }

【问题讨论】:

    标签: android asynchronous android-asynctask


    【解决方案1】:

    如果您在 API 11 (3.0) 或更高版本中运行,您可以将您的 handler.execute(counter_URL + code); 更改为 handler.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, counter_URL + code);

    这允许同时运行多个 AsyncTask。

    【讨论】:

    • 这对我有用!你能解释一下这是如何解决这个问题的吗?这是否意味着我的主线程被 handler.get() 卡住了?谢谢~
    • Android 默认只允许一次运行 1 个 AsyncTask(也许是为了避免多线程问题?不太确定)。在 API 11 中,他们引入了 executeOnExecutor 方法,该方法实质上允许同时执行多个 AsyncTask 实例。
    • 但我原来的 handler.get() 只是不停地加载而不是加载缓慢。所以我不知道为什么多线程有帮助?谢谢~
    • 当你的 'handler.execute()' 到达 'HttpResponse response = client.execute(get);'在 doInBackground 中,它无法执行,因为它正在等待来自初始 AsyncTask 的“onPostExecute()”回调,它永远无法到达,因为此时您正在等待来自第二个 AsyncTask 的 HttpResponse,然后再继续。
    【解决方案2】:

    在doinbackground()中使用asynctask类的发布进度方法,而不是直接调用“handler.execute”。

    在 onprogressupdate() 中调用“handler.execute”,在 doInBackground 中调用发布进度。

    【讨论】:

    • 你能解释一下“使用发布进度方法”吗?谢谢~
    【解决方案3】:

    这是发布进度的示例:

    private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
    

    }

    如果对您有帮助,请投票或标记为 true。

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 2017-12-06
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多