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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With