从AsynTask作业访问MainActivity中的变量

时间:2015-08-16 23:44:10

标签: java android android-asynctask static-variables

我的应用从API获取数据并将其添加到ArrayList<String>以解析它并在UI中向用户显示。 我创建了ArrayList static,然后我像MainActivity.arrayList.add(link);那样访问它,但我被告知static variables是邪恶的,我不应该使用它们。另外,如果我使用setter和getter,它必须是{ {1}}从另一个类访问它。 我正在考虑将我需要的所有内容修改为static,然后将其从AsyncTask返回到doInBackground,但我认为这不是最好的方法它。 还有另一种方法吗?

2 个答案:

答案 0 :(得分:1)

从AsyncTask访问Activity变量的最佳实践和首选方法是,在onProgressUpdate和onPostExecute方法中访问它们。因为Activities,onProgressUpdate和onPostExecute在UI线程上运行,但doInBackground方法在单独的线程上运行。从单独的线程访问变量可能会很痛苦。此外,静态变量定义必须设计得很好,因为类的所有实例都使用相同的静态变量实例。

您最好在asynctask中添加一个回调接口来处理其结果。

让我举个例子;

我从Google's site复制了下面的asynctask。并通过添加界面进行修改:

private static class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

     interface OnDownloadListener {
         void onDownloadFinished(long bytes);
         void onDownloadProgressUpdate(int progress);
     }

     private OnDownloadListener mDownloadListener;
     public DownloadFilesTask (OnDownloadListener onDownloadListener) {
         mOnDownloadListener = onDownloadListener;
     }

     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) {
         mOnDownloadListener.onDownloadProgressUpdate(progress);
     }

     protected void onPostExecute(Long result) {
         mOnDownloadListener.onDownloadFinished(result);
     }
 }

在您的活动中,实现接口,并将活动发送到asynctask的构造函数:

public class SomeActivity extends Activity implements OnDownloadListener {

  // activity's logic here

  // create an instance of the asyncTask
  DownloadFilesTask downloadFilesTask = new DownloadFilesTask(this);


  // OnDownloadListener interface implementation
  void onDownloadFinished(long bytes) {
      // handle asyncTasks onPostExecute method, you can reach non static variables here.     
  }

  void onDownloadProgressUpdate(int progress) {
      // handle asyncTasks onProgressUpdate method, you can reach non static variables here.
  }
}

据我所知,这是处理asynctask结果的最简单和首选方法。

答案 1 :(得分:-1)

截至2019年7月25日 这是我的解决方案:

dns

希望这会有所帮助。

相关问题