我有下面的片段,它加载了很多数据,这个片段有一个内部静态类,它以以下方式扩展AsyncTask,对片段本身进行弱引用,以防止内存泄漏:
public class PokemonDescriptionFragment extends Fragment {
////////Code
private static class LoadPokemonData extends AsyncTask<Void, Void, Pokemon> {
private WeakReference<PokemonDescriptionFragment> appReference;//FIXME Should I pass fragment as weak reference?
LoadPokemonData(PokemonDescriptionFragment context) {
appReference = new WeakReference<>(context);
}
/**
* Executed before starting the BACKGROUND THREAD
* Executed in the MAIN THREAD
*/
@Override
protected void onPreExecute() {
final PokemonDescriptionFragment fragment = appReference.get();
if (fragment == null) return;
GenericUtils.changeVisibility(View.VISIBLE, fragment.pokedexDataProgressBar, fragment.biologyProgressBar, fragment.statsDataProgressBar, fragment.abilitiesProgressBar, fragment.etymologyProgressBar);
GenericUtils.changeVisibility(View.GONE, fragment.llPokedexContainer);
}
/**
* Executes after onPreExecute.
* Is executed in the BACKGROUND THREAD
* Here you can call "publishProgress" method that executes the "onProgressUpdate" method in Main thread ,
* however , in this case , as I use indeterminated progress bar isn't necessary
*
* @return its sends the values to "onPostExecute"
*/
@Override
protected Pokemon doInBackground(Void... params) {
final PokemonDescriptionFragment fragment = appReference.get();
if (fragment == null) return null;
fragment.initializePokemonData();
return fragment.selectedPokemon;
}
/**
* Executes after doInBackground
* Executed in the MAIN THREAD
*/
@Override
protected void onPostExecute(Pokemon pokemon) {
final PokemonDescriptionFragment fragment = appReference.get();
if (fragment == null) return;
if (Objects.nonNull(pokemon)) {
MainActivity.setSelectedPokemon(pokemon);
fragment.abilityAdapter.refreshAbilities(fragment.abilityList);
}
GenericUtils.changeVisibility(View.GONE, fragment.pokedexDataProgressBar, fragment.biologyProgressBar, fragment.statsDataProgressBar, fragment.abilitiesProgressBar, fragment.etymologyProgressBar);
GenericUtils.changeVisibility(View.VISIBLE, fragment.llPokedexContainer);
fragment.displayFullData();
}
}
然而,我不确定这是否是100%安全的,我将片段作为弱引用传递,因为我需要访问片段所具有的一些方法和属性。此外,如果你检查我的代码,我会声明3次:
final PokemonDescriptionFragment fragment = appReference.get();
if (fragment == null) return null;
在异步任务中,而不是将其声明为异步任务的全局属性并在3个方法中引用它,这是正确的吗?如果我将其添加为Asny任务的全局属性,会有什么问题吗?
在AsyncTask
中添加Fragment
作为WeakReference
是安全的,不应该是内存泄漏的问题。
此外,最好取消碎片onDestroy()
中的AsyncTask
,以免浪费资源。
但是,考虑完全重构代码,以获得更好的体系结构,从而完全避免在AsyncTask中需要Fragment上下文。