This is the second part of the Bluetooth series tutorials. We continue where we left of from the first part, Turn Bluetooth service on the Android device ON and OFF

After thats done, first thing that we should do is adding a SCAN button in the layout and in the MainActivity. We are going to use simple button for this example and bind that button with our favorite library ButterKnife with @OnClick annotation.

Here is the layout file upgradet with the new SCAN button and Recycler View element:

And here is the button in our MainActivity:

As you can see we use a new static method declared in our Bluetooth Manager class called scan that receive BluetoothAdapter and Context as arguments. The bluetoothAdapter is instantiated in our onCreate method, explained in part 1.

Here is the new .scan() method in BluetoothManager class:

When this method is called, first we are starting the discovery of detectable bluetooth devices. The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name. This is an asynchronous call, it will return immediately.

Next we add IntentFilter that is translated in XML form for registration of our BroadcastReceiver to listen to newly discovered bluetooth devices. After that we register an receiver to our activity with .registerReceiver method, passing, previously initialized BluetoothBroadcastReceiver in our BluetoothManager class:

As that been said, we move on to describe how our BluetoothBroadcastReceiver works:

The Broadcast Receiver component is explained in this post before: Third Android Component – Broadcast Receiver.  After we check for action found with our registered intent filter, we are getting the nearby blluetooth devices. Adding only the name and MAC address in our created Device model, for trigering an event so that our MainActivity can listen when some device is discovered and add that device in list.

Here is the Device model. In here we override equals() and hashCode() so we can compare when device is turned ON and OFF and ON again, so it wont appear twice or more times in our discovered bluetooth devices:

And the EventHandler class for listening when device is discovered and trasfer device`s info to our MainClass (NOTE: EventBus is also a useful Android library):

And here how is handled the event in our MainClass with EventBus registering and unregistering :

Here is explanation how to create Recycler View and Adapter with Model so you can create and diplay the List of discovered devices.

 

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *