intentfilter

IntentFilter在Fragment中如何使用

小樊
83
2024-07-03 12:03:14
栏目: 编程语言

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

0
看了该问题的人还看了