AsyncTask:doInBackground()的返回值在哪里?

Dhr*_*ada 61 android return-value android-asynctask

调用时AsyncTask<Integer,Integer,Boolean>,其返回值为:

protected Boolean doInBackground(Integer... params)

通常我们启动AsyncTask new AsyncTaskClassName().execute(param1,param2......);但它似乎没有返回值.

哪里可以doInBackground()找到返回值?

Kon*_*rov 62

然后可以在onPostExecute中使用该值,您可能希望覆盖该值以便使用结果.

以下是Google文档的示例代码段:

 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));
          }
          return totalSize;
      }

      protected void onProgressUpdate(Integer... progress) {
          setProgressPercent(progress[0]);
      }

      protected void onPostExecute(Long result) {
          showDialog("Downloaded " + result + " bytes");
      }
 }
Run Code Online (Sandbox Code Playgroud)

  • 为了实现除了记录或显示对话框之外的任何实际用途,您可以在UI(或其他)类中嵌套扩展`AsyncTask`的类,然后使用`onPostExecute中的返回值从该类调用方法`方法. (8认同)

Cyr*_*oux 34

您可以doInBackground()通过调用类的get()方法来检索受保护的布尔值的返回值AsyncTask:

AsyncTaskClassName task = new AsyncTaskClassName();
bool result = task.execute(param1,param2......).get(); 
Run Code Online (Sandbox Code Playgroud)

但要小心UI的响应性,因为get()等待计算完成并将阻止UI线程.
如果您正在使用内部类,则最好将该作业放入onPostExecute(布尔结果)方法中.

如果您只想更新用户界面,请AsyncTask为您提供以下两种选择:

  • 要与执行的任务并行更新UI doInBackground()(例如更新a ProgressBar),您必须publishProgress()doInBackground()方法内部调用.然后,您必须更新onProgressUpdate()方法中的UI .
  • 要在任务完成时更新UI,您必须在onPostExecute()方法中执行此操作.

    /** This method runs on a background thread (not on the UI thread) */
    @Override
    protected String doInBackground(String... params) {
        for (int progressValue = 0; progressValue  < 100; progressValue++) {
            publishProgress(progressValue);
        }
    }
    
    /** This method runs on the UI thread */
    @Override
    protected void onProgressUpdate(Integer... progressValue) {
        // TODO Update your ProgressBar here
    }
    
    /**
     * Called after doInBackground() method
     * This method runs on the UI thread
     */
    @Override
    protected void onPostExecute(Boolean result) {
       // TODO Update the UI thread with the final result
    }
    
    Run Code Online (Sandbox Code Playgroud)

    这样您就不必关心响应问题了.

    • 这是正确的方法.get()将冻结UI你可以建议任何其他选项我想使用异步任务的返回结果然后想要exucute其他web servecice请帮助我 (3认同)
    • 如果您阅读超出第五行的帖子,您会看到我建议使用`OnPostExecute()`而不是`get()`来避免阻塞UI线程. (3认同)