在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()方法中注銷了廣播接收器。