在Fragment中使用IntentFilter需要在Fragment的onCreateView()方法中注册IntentFilter,并在onDestroyView()方法中注销IntentFilter。以下是一个简单的示例:
public class MyFragment extends Fragment { private BroadcastReceiver receiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my, container, false); IntentFilter filter = new IntentFilter(); filter.addAction("com.example.MY_ACTION"); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 处理接收到的广播 } }; getActivity().registerReceiver(receiver, filter); return view; } @Override public void onDestroyView() { super.onDestroyView(); getActivity().unregisterReceiver(receiver); } }
在上面的示例中,我们在onCreateView()方法中注册了一个接收指定action的IntentFilter,并创建了一个BroadcastReceiver来处理接收到的广播。在onDestroyView()方法中注销了广播接收器。