Recipe 4.8 Enabling Bluetooth

Android Versions
Level 1 and above
Permissions
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
Source Code Download from Wrox.com
Bluetooth.zip

If you are writing a Bluetooth application, you can programmatically enable the Bluetooth radio on the device. This recipe shows you two ways to accomplish this.

Solution

Before attempting to use the Bluetooth radio on the device, it is recommended that you first check whether Bluetooth is available on it. This recipe will show you how to:

  • Check if the Bluetooth radio is available on the device
  • Enable the Bluetooth radio if it is available
  • Monitor the state of the Bluetooth radio on the device

Checking for Bluetooth Availability

To check for Bluetooth availability on the device, you create a variable of type BluetoothAdapter. To instantiate the BluetoothAdapter class, you call the BluetoothAdapter.getDefaultAdapter() method. If Bluetooth is not available on the device, then the BluetoothAdapter.getDefaultAdapter() method will return a null. The following code snippet illustrates this:

package net.learn2develop.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    BluetoothAdapter bluetoothAdapter;
    //---check if bluetooth is available on the device---
    private boolean BluetoothAvailable()
    {
        if (bluetoothAdapter == null) 
 return false; ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.