为了减轻内存泄漏,我们在运行在不同线程上的内部类中保留活动的弱引用。我们检查weakreference.get() 是否为非空,然后再继续。如果当我们检查weakreference.get() 为非空但发生垃圾回收时,我们是否需要一次又一次地检查引用是否为非空,或者我是否遗漏了什么?
public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyAsyncTask(this).execute();
}
private static class MyAsyncTask extends AsyncTask {
private WeakReference<MainActivity> mainActivity;
public MyAsyncTask(MainActivity mainActivity) {
this.mainActivity = new WeakReference<>(mainActivity);
}
@Override
protected Object doInBackground(Object[] params) {
return doSomeStuff();
}
@Override
protected void onPostExecute(Object object) {
super.onPostExecute(object);
if (mainActivity.get() != null){
//do something
//context switching and garbage collection happen
//again do a null check?
}
}
}
}