Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to registerReceiver in Fragment

I show Bluetooth devices in a ListView. I tried it in an Activity before and it worked, but now I have to include this ListView in a Fragment

It´s clear that one or two things don´t belong here, like the registerReceiver, unregisterReceiver and RESULT_CANCELED.

protected void onResume() {
    registerReceiver(receiver, filter);
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
     filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
     filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);


}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_CANCELED){
            Toast.makeText(getActivity()     , "El Bluetooth debe estar activado para continuar", Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }
    }

The lines that start with registerReceiver, unegisterReceiver and if(resultCode==RESULT_CANCELED){ are giving me problems.

As an aditional fact, I have tried to to change it to an Activity instead of a Fragment, but my Main class have an error with that because I am working with Fragments.

like image 1000
Pamme Cobos Avatar asked Sep 03 '15 14:09

Pamme Cobos


People also ask

Where do I register broadcast receiver in fragment?

Conclusion: So it is better to register the receiver only inside onResume() and unregister inside onPause() because onCreateView() deals with view hierarchy only. It has nothing to do with receiver.

What is the use of broadcast receiver in Android?

A broadcast receiver (receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens.


1 Answers

All these methods and variables belong to Activity class. So consider calling them with context of parent Activity of Fragment.

You may call required methods as:

 requireActivity().registerReceiver(receiver, filter);

and

 requireActivity().unregisterReceiver(receiver);

if(resultCode==RESULT_CANCELED){

can be replaced with

if(resultCode == Activity.RESULT_CANCELED){

Hope this solve your problem.

like image 96
uniruddh Avatar answered Sep 21 '22 17:09

uniruddh