0

I have one button in fragment. When i click on that button - register broadcast and display available bluetooth devices in log. When i am working with below code, receiver is not being registered. Thanks in advance.

Below is my code.

Method to call when button clicked:

private void buttonGetsClicked() {
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    getActivity().registerReceiver(bleDiscovery, filter);
    if (mBluetoothAdapter.isDiscovering())
    {
        mBluetoothAdapter.cancelDiscovery();
    }
    mBluetoothAdapter.startDiscovery();
}

Broadcast receiver:

private BroadcastReceiver bleDiscovery = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("receivecalled","receiver called");
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // Discovery has found a device. Get the 
                    // object and its info from the Intent.
                    BluetoothDevice device = 
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    String deviceName = device.getName();
                    String deviceHardwareAddress = device.getAddress(); // 
MAC address

                    Log.d("device Name","device Name"+deviceName);
                    Log.d("device id","device Id"+deviceHardwareAddress);
                }
    }
};
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Eswar
  • 199
  • 1
  • 13
  • Show your `Manifest` file, not sure if you have defined permission in the manifest – Taseer Jul 23 '19 at 13:02
  • Try to register the broadcast in onResume method and unregister in onPause method in Fragment rather than register on button click. Here is the reference https://stackoverflow.com/a/16617831/1556997 – Mitesh Sardhara Jul 23 '19 at 13:30
  • @TaseerAhmad - These are that i have defined in manifest file. ' ' – Eswar Jul 23 '19 at 15:55
  • @MiteshSardhara - Even i did that. registered in onResume() and unregistered in onPasue(). But doesn't work as expected. – Eswar Jul 23 '19 at 15:57
  • Can you try putting pause between cancelDiscovery() and startDiscovery() method and make sure that peer device is in discoverable mode. – Vivek Mangal Aug 22 '19 at 07:26

0 Answers0