我在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后注销了接收者,它现在可以工作。我用代码编辑。
最佳答案
您将从片段中的unregisterReceiver
方法调用onPause
。