我在 FragmentInfo 类中实现了 onReceive 方法,因为当意图从我的代码中的其他地方发送时,我需要更新 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 后取消注册接收器,它现在可以工作了。我在代码中编辑。