【发布时间】:2018-03-11 06:54:56
【问题描述】:
我想使用WeakReference 方法来避免我的AsyncTask 泄漏内存。我在网上和 Stackoverflow 上找到了示例,但它们仅在 onPostExecute 中获得参考,我不确定如何在所有 3 种 UI 方法中正确使用它。
我目前的方法是这样的,但我不知道是否可以摆脱一些冗余。为什么我不能只在构造函数中调用activityReference.get(),然后只在每个 UI 方法中检查 null?为什么在线示例在使用WeakReference 之前调用get?
private static class ExampleAsyncTask extends AsyncTask<Integer, Integer, String> {
private WeakReference<MainActivity> activityReference;
ExampleAsyncTask(MainActivity context) {
activityReference = new WeakReference<>(context);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(Integer... integers) {
for (int i = 1; i < integers[0]; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress((i * 100) / integers[0]);
}
return "Finished";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
MainActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
MainActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) {
return;
}
activity.progressBar.setProgress(0);
activity.progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
【问题讨论】:
标签: android android-asynctask weak-references