Android我应该在异步任务中将片段作为弱引用传递吗?

问题描述

我有以下片段,该片段加载大量数据,该片段具有内部静态类,该类通过以下方式扩展AsyncTask,但对片段本身to prevent memory leaks的引用较弱:

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.etymologyProgressBar);
        GenericUtils.changeVisibility(View.VISIBLE,fragment.llPokedexContainer);
        fragment.displayFullData();
    }

}

但是,我不确定这是否100%安全,我将该片段作为弱引用传递,因为我需要访问该片段具有的一些方法和属性。此外,如果您检查我的代码,我会声明3次: / p>

  final PokemonDescriptionFragment fragment = appReference.get();
    if (fragment == null) return null;

在异步任务中,而不是将其声明为异步任务的全局属性并在3种方法中对其进行引用,这是正确的吗?如果将其添加为Asny任务的全局属性,有什么问题吗?

解决方法

Fragment中将WeakReference作为AsyncTask添加是安全的,就内存泄漏而言,这不是问题。

此外,最好取消片段AsyncTask中的onDestroy(),以免浪费资源。

但是请考虑完全重构代码,以获得更好的architecture,从而完全避免在AsyncTask中使用Fragment上下文。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...