Scanning bluetooth devices android

How to scan for available bluetooth devices in range in android?

I need to get a list of available bluetooth devices in the area using google android 2.1. Thing is, i don’t just need a list of those devices, i need some unique id for each device found and i need an indicator, how «good» the signal is received (like the «level» in android.wifi.ScanResult). How do i do that?

4 Answers 4

mBluetoothAdapter.startDiscovery(); mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); //Finding devices if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> >; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); 

@SaharMillis: What about it doesn’t work for you? It works fine, but your other device needs to be discoverable, not just with bluetooth on.

how does this work if there are multiple bluetooth devices found in the range. Does the receiver get triggered multiple times?

@Zapnologica the BroadcastReceiver gets notified once per device; therefore one has to keep them in an ArrayList field, or alike. while there are two? further actions available, beside the BluetoothDevice.ACTION_FOUND , of which one indicates the scan being complete.

Call method bluetoothScanning, context is required

void bluetoothScanning() < IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.startDiscovery(); >// Create a BroadcastReceiver for ACTION_FOUND. private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Discovery has found a device. Get the BluetoothDevice // 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.i("Device Name: " , "device " + deviceName); Log.i("deviceHardwareAddress " , "hard" + deviceHardwareAddress); >> >; 

Name: LE-Bose Revolve+ SoundLink deviceHardwareAddress: MAC .

@GregD this is my exact problem. it was working fine, but then it started to show only mac addresses and not names. can’t figure out why

This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.

Make sure you import BeaconManager

private BeaconManager beaconManager; //In onCreate method beaconManager = BeaconManager.getInstanceForApplication(this); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); //use these out of the onCreate method public void onScanStart(View view) < stopScanButton.setEnabled(true); scanningButton.setEnabled(false); beaconManager.bind(this); >@Override public void onBeaconServiceConnect() < beaconManager.removeAllRangeNotifiers(); beaconManager.addRangeNotifier(new RangeNotifier() < @Override public void didRangeBeaconsInRegion(Collectionbeacons, Region region) < for (Beacon b : beacons) < System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi())); >); try < //Tells the BeaconService to start looking for beacons that match the passed. beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); >catch (RemoteException e) < Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); >> 

Let me know if that works for you!

To able to discovery devices by bluetooth. Make sure you

  • Enable bluetooth
  • Allow required permissions for your application (some permission is runtime permission). You can check here https://developer.android.com/about/versions/12/features/bluetooth-permissions
Читайте также:  Автоматическое сопряжение bluetooth android

AndroidManifest.xml

MainActivity

class MainActivity : AppCompatActivity() < private var bluetoothAdapter: BluetoothAdapter? = null private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() < override fun onReceive(context: Context?, intent: Intent) < val action = intent.action Log.i("TAG", "onReceive $action") if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) < Log.i("TAG", "Discovery finished, hide loading") >else if (BluetoothDevice.ACTION_FOUND == action) < val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) Log.i("TAG", "Device Name: " + (device?.name ?: "")) Log.i("TAG", "Device Address:" + (device?.address ?: "")) > > > override fun onCreate(savedInstanceState: Bundle?) < . findViewById(R.id.button_start_discovery).setOnClickListener < if (bluetoothAdapter == null) < initBluetoothDiscovery() >startDiscovery() > > private fun initBluetoothDiscovery() < val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothAdapter = bluetoothManager.adapter val intentFilter = IntentFilter().apply < addAction(BluetoothDevice.ACTION_FOUND) addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) >registerReceiver(bluetoothReceiver, intentFilter) > private fun startDiscovery() < if (bluetoothAdapter?.isDiscovering == true) < Log.i("TAG", "cancel start discovery") bluetoothAdapter?.cancelDiscovery() >Log.i("TAG", "start discovery, show loading") bluetoothAdapter?.startDiscovery() > override fun onDestroy() < super.onDestroy() bluetoothAdapter?.cancelDiscovery(); unregisterReceiver(bluetoothReceiver); >> 

Источник

Create a Bluetooth Scanner With Android’s Bluetooth API

Matthew Kim

Matthew Kim Last updated Jul 13, 2015

Bluetooth has become a very popular technology, especially on mobile devices. It’s a technology to discover and transfer data between nearby devices. Virtually every modern mobile device has Bluetooth capabilities these days. If you want to make an app interface with another Bluetooth enabled device, ranging from phones to speakers, you must know how to use Android’s Bluetooth API.

In this tutorial, we will be making an app that is similar to the built-in Bluetooth app in Android’s settings. It will include the following features:

  • enable Bluetooth on a device
  • display a list of paired devices
  • discover and list nearby Bluetooth devices

We will also go over the basics to connect and send data to another Bluetooth device. I’ve created a project to get us started, which you can download from GitHub. The below screenshot illustrates what the starter project looks like. If you get stuck or run into problems, then you can take a look at the finished project on GitHub.

Pre App What the starter code given produces

1. Enabling Bluetooth

Before we can enable Bluetooth on an Android device, we need to request the necessary permissions. We do this in the app’s manifest. The BLUETOOTH permission allows our app to connect, disconnect, and transfer data with another Bluetooth device. The BLUETOOTH_ADMIN permission allows our app to discover new Bluetooth devices and change the device’s Bluetooth settings.

manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package color: #f4bf75">com.tutsplus.matt.bluetoothscanner" > 
 android.permission.BLUETOOTH" /> 
 android.permission.BLUETOOTH_ADMIN" /> 

We will use the Bluetooth adapter to interface with Bluetooth. We instantiate the adapter in the ListActivity class. If the adapter is null , this means Bluetooth is not supported by the device and the app will not work on the current device. We handle this situation by showing an alert dialog to the user and exiting the app.

protected void onCreate(Bundle savedInstanceState)  
BTAdapter = BluetoothAdapter.getDefaultAdapter(); 
// Phone does not support Bluetooth so let the user know and exit. 
new AlertDialog.Builder(this) 
.setMessage("Your phone does not support Bluetooth") 
.setPositiveButton("Exit", new DialogInterface.OnClickListener()  
public void onClick(DialogInterface dialog, int which)  
.setIcon(android.R.drawable.ic_dialog_alert) 

If Bluetooth is available on the device, we need to enable it. To enable Bluetooth, we start an intent provided to us by the Android SDK, BluetoothAdapter.ACTION_REQUEST_ENABLE . This will present a dialog to the user, asking them for permission to enable Bluetooth on the device. REQUEST_BLUETOOTH is a static integer we set to identify the activity request.

public class ListActivity extends ActionBarActivity implements DeviceListFragment.OnFragmentInteractionListener  
public static int REQUEST_BLUETOOTH = 1; 
protected void onCreate(Bundle savedInstanceState)  
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
startActivityForResult(enableBT, REQUEST_BLUETOOTH); 

2. Obtaining a List of Paired Devices

In this step, we scan for paired Bluetooth devices and display them in a list. In the context of a mobile device, a Bluetooth device can either be:

It is important to know the difference between a paired and a connected Bluetooth device. Paired devices are aware of each other’s existence and share a link key, which can be used to authenticate, resulting in a connection. Devices are automatically paired once an encrypted connection is established.

Connected devices share an RFCOMM channel, allowing them to send and receive data. A device may have many paired devices, but it can only be connected to one device at a time.

Bluetooth devices are represented by the BluetoothDevice object. A list of paired devices can be obtained by invoking the getBondedDevices() method, which returns a set of BluetoothDevice objects. We invoke the getBondedDevices() method in the DeviceListFragment ‘s onCreate() method.

public void onCreate(Bundle savedInstanceState)  
super.onCreate(savedInstanceState); 
Log.d("DEVICELIST", "Super called for DeviceListFragment onCreate\n"); 
deviceItemList = new ArrayListDeviceItem>(); 
SetBluetoothDevice> pairedDevices = bTAdapter.getBondedDevices(); 

We use the getName() and getAddress() methods to obtain more information about the Bluetooth devices. The getName() method returns the public identifier of the device while the getAddress() method returns the device’s MAC address, an identifier uniquely identifying the device.

Now that we have a list of the paired devices, we create a DeviceItem object for each BluetoothDevice object. We then add each DeviceItem object to an array named deviceItemList . We’ll use this array to display the list of paired Bluetooth devices in our app. The code for displaying the list of DeviceItem objects is already present in the starter project.

for (BluetoothDevice device : pairedDevices)  
DeviceItem newDevice= new DeviceItem(device.getName(),device.getAddress(),"false"); 
deviceItemList.add(newDevice); 

3. Discover Nearby Bluetooth Devices

The next step is to discover devices the device isn’t paired with yet, unknown devices, and add them to the list of paired devices. We do this when the user taps the scan button. The code to handle this is located in DeviceListFragment .

We first need to make a BroadcastReceiver and override the onReceive() method. The onReceive() method is invoked whenever a a Bluetooth device is found.

The onReceive() method takes an intent as its second argument. We can check what kind of intent is broadcasting with by invoking getAction() . If the action is BluetoothDevice.ACTION_FOUND , then we know we have found a Bluetooth device. When this occurs, we create a DeviceItem object using the device’s name and MAC address. Finally, we add the DeviceItem object to the ArrayAdapter to display it in our app.

public class DeviceListFragment extends Fragment implements AbsListView.OnItemClickListener 
private final BroadcastReceiver bReciever = new BroadcastReceiver()  
public void onReceive(Context context, Intent intent)  
String action = intent.getAction(); 
if (BluetoothDevice.ACTION_FOUND.equals(action))  
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
DeviceItem newDevice = new DeviceItem(device.getName(), device.getAddress(), "false"); 

When the scan button is toggled on, we simply need to register the receiver we just made and invoke the startDiscovery() method. If the scan button is toggled off, we unregister the receiver and invoke cancelDiscovery() . Keep in mind that discovery takes up a lot of resources. If your application connects with another Bluetooth device, you should always cancel discovery prior to connecting.

We also clear the ArrayAdapter object, mAdapter , when discovery begins. When we start scanning, we don’t want to include old devices that may no longer be in range of the device.

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState)  
View view = inflater.inflate(R.layout.fragment_deviceitem_list, container, false); 
ToggleButton scan = (ToggleButton) view.findViewById(R.id.scan); 
scan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()  
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)  
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
getActivity().registerReceiver(bReciever, filter); 
getActivity().unregisterReceiver(bReciever); 

That’s it. We have finished our Bluetooth scanner.

4. Connecting to a Device

Bluetooth connections work like any other connection. There is a server and a client, which communicate via RFCOMM sockets. On Android, RFCOMM sockets are represented as a BluetoothSocket object. Fortunately for us, most of the technical code for servers is handled by the Android SDK and available through the Bluetooth API.

Connecting as a client is simple. Your first obtain the RFCOMM socket from the desired BluetoothDevice by calling createRfcommSocketToServiceRecord() , passing in a UUID, a 128-bit value that you create. The UUID is similar to a port number.

For example, let’s assume you are making a chat app that uses Bluetooth to chat with other nearby users. To find other users to chat with, you would want to look for other devices with your chat app installed. To do this, we would look for the UUID in the list of services of the nearby devices. Using a UUID to listen and accept Bluetooth connections automatically adds that UUID to the phone’s list of services, or service discovery protocol.

Once the BluetoothSocket is created, you call connect() on the BluetoothSocket . This will initialize a connection with the BluetoothDevice through the RFCOMM socket. Once our device is connected, we can use the socket to exchange data with the connected device. Doing this is similar to any standard server implementation.

Maintaining a Bluetooth connection is costly so we need to close the socket when we no longer need it. To close the socket, we call close() on the BluetoothSocket .

The following code snippet shows how to connect with a given BluetoothDevice :

public class ConnectThread extends Thread 
private BluetoothSocket bTSocket; 

Источник

Оцените статью
Adblock
detector