Pamme Cobos Pamme Cobos - 1 year ago 239
Android Question

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.

Answer Source

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:

 getActivity().registerReceiver(receiver, filter);

and

 getActivity().unregisterReceiver(receiver);

if(resultCode==RESULT_CANCELED){

can be replaced with

if(resultCode == Activity.RESULT_CANCELED){

Hope this solve your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download