如何取消注册片段中使用的Receiver?

时间:2013-07-26 07:37:07

标签: java android broadcastreceiver

我在FragmentInfo类中实现了onReceive方法,因为当我的代码中的其他地方发送intent时,我需要更新UI。我从Fragment注册这个接收器,但是从MainActivity注册,因为它必须从Activity注册。我不知道在哪里放置unregisterReceiver,所以我的程序崩溃了。我收到了错误:

MainActivity泄露了最初在此处注册的IntentReceiver FragmentInfo。你是否错过了对unregisterReceiver()的调用?

我试图从MainActivity onPause方法调用unregisterReceiver,就像通常那样,但是从MainActivity我无法访问mBroadcastReceiver。我该如何解决这个问题?

public class FragmentInfo extends Fragment {

    //nested class BroadcastReceiver
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        //from there we must update FragmentInfo UI
        @Override
        public void onReceive(Context context, Intent intent) {
            //updateFragmentInfo(intent);
            updateUiInfo();
            //unregisterReceiver
        ((MainActivity)getActivity()).unregisterReceiver(mBroadcastReceiver);
        }
    };

    private TextView textView3;
    private TextView textView5;
    private TextView textView7;
    private TextView textView8;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
        //dynamic register BroadcastReceiver, for triggering intent when BT connection is established
        //BroadcastReceiver can be registered static in ManifestFile
        IntentFilter mIntentFilter = new IntentFilter();
        //register message 
        mIntentFilter.addAction("bluetooth_established_intent");
        //we must call registerReceiver from MainActivity!
        ((MainActivity)getActivity()).registerReceiver(this.mBroadcastReceiver,mIntentFilter);
    }
}

编辑:我在调用updateUIInfo后取消注册接收器,现在可以正常工作了。我在代码中进行编辑。

4 个答案:

答案 0 :(得分:0)

您将从片段中的unregisterReceiver方法中调用onPause

答案 1 :(得分:0)

好的做法是在onResume中注册广播接收器并在onPause中注销。因此,每当片段对用户可见时,它就会注册接收器,并且每次它变得不可见(被移除或替换为另一个片段)时,它会取消注册接收器。

答案 2 :(得分:0)

尝试通过以下方法调用unregisterReceiver

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

答案 3 :(得分:0)

我设法以这种方式最终解决了泄漏问题:

LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(YOUR_RECEIVER_HERE);

因为做了

getActivity().unregisterReceiver(...) 

getContext().unregisterReceiver(...)
<{1}}和onPause()中的

没有帮助。