Fragment的BroadcastReceiver在一个单独的类中

时间:2018-02-22 16:58:07

标签: android

我的一个片段变得非常大,所以我决定将BroadcastReceiver移动到一个单独的类。所以我需要在接收器中引用我的Fragment来发送更新(我知道有不同的方法来实现这一点,但主要关注的是引用和泄漏)。

我想知道我是否需要在这里使用WeakReference或强引用是好的。据说,如果两个对象彼此有引用,那么它们就不能被GC编辑。

广播接收器:

public class FragmentReceiver extends BroadcastReceiver
{
    private WeakReference<YourFragment> yourFragmentWeakReference;
// Or strong reference?

    public FragmentReceiver(YourFragment yourFragment) {
        this.yourFragmentWeakReference = new WeakReference<>(yourFragment);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action != null && action.equals("AllTasksFragmentUpdate"))
        {
            YourFragment yourFragment = yourFragmentWeakReference.get();
            if (yourFragment != null){
                yourFragment.doSomething();
            }
        }
    }
}

片段:

public class YourFragment extends Fragment{

    private FragmentReceiver fragmentReceiver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragmentReceiver = new FragmentReceiver(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getContext() != null) 
            LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(fragmentReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getContext() != null)
            LocalBroadcastManager.getInstance(getContext()).registerReceiver(fragmentReceiver, new IntentFilter("AllTasksFragmentUpdate"));
    }
}

我想我可以在onDestroyView中使用强引用并清除fragmentReceiver吗?

@Override
public void onDestroyView() {
    super.onDestroyView();
    fragmentReceiver = null;
}

编辑:它应该是onDestroy而不是onDestroyView。正如Krish所提到的,onDestroyView被调用为后台堆栈中的一个片段,它将在前景跳过onCreate时执行onCreateView。

0 个答案:

没有答案