Recipe 6.9 Checking for the Availability of Bluetooth

Android Versions
Level 1 and above
Permissions
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
Source Code to Download at Wrox.com
TurnOnBluetooth.zip

Most Android devices on the market today support Bluetooth connectivity. Bluetooth is useful for short-range communication when you need to exchange small packets of data between devices. In the following few recipes, you will learn how to develop Android applications that communicate over Bluetooth. This recipe shows how to determine whether the Bluetooth radio is available on the target device.

Solution

To use the Bluetooth functionality in your application, you need to add the following two permissions in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Then, declare the following objects:

    BluetoothAdapter bluetoothAdapter;
    static final int REQUEST_ENABLE_BT = 0;

The BluetoothAdapter object is used to represent the Bluetooth adapter on your device. Once you have this object instantiated, you can get the list of pair devices on your device, create a listening socket, and so on.

To instantiate the BluetoothAdapter object, use the getDefaultAdapter() method of the BluetoothAdapter class:

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

To determine whether Bluetooth is available on your device, simply check whether the ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.