Android Bluetooth Enable Disable Example

0

In this article, I am going to show you how to programmatically turn on/off bluetooth in android. Android provides Bluetooth APIs to perform the following:

  1. Setting up Bluetooth. Turning it on/off.
  2. Finding devices that are already paired
  3. Discovering new devices to connect
  4. Connecting devices
  5. Transferring data between devices

We will work on the first case to view the current bluetooth status, turn it on or off.

Bluetooth button

Our layout consists of just an image button and a text describing the status. We will change the image of the button based on the bluetooth status. If already enabled, we will show a green bulb. If disabled, we will show a red bulb. If blue tooth not available, we show a disabled grey button.

Bluetooth Button

Bluetooth Button

bluetooth_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/bluetooth_status_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/grey_button" 
        android:contentDescription="@string/bluetooth_status"/>

    <TextView
        android:id="@+id/bluetooth_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/bluetooth_status"/>

</LinearLayout>

BluetoothAdapter API

You will find all of the bluetooth APIs in the android.bluetoothpackage. The BluetoothAdapter is the entry-point for all Bluetooth interaction. First we need to get the BluetoothAdapter using the static method BluetoothAdapter.getDefaultAdapter(). This returns a BluetoothAdapter that represents the device’s own Bluetooth adapter.

Main Activity

BluetoothEnableDisableActivity is our main activity. If bluetooth is not available, we will set the button’s image to a grey bulb. If bluetooth is disabled, the button will be shown as red bulb. If it is enabled, the button will be shown as green bulb. We also add a listener to the button so that one can turn on and off the bluetooth.
Note that if bluetooth is unavailable, the button will be disabled.

BluetoothEnableDisableActivity:

package com.javarticles.android;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothEnableDisableActivity extends Activity {
	private BluetoothAdapter mBluetoothAdapter;
	private ImageButton mBluetoothStatusBtn;
	private TextView mBluetoothStatusText;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetooth_layout);
		
		mBluetoothStatusBtn = (ImageButton) findViewById(R.id.bluetooth_status_button);
		mBluetoothStatusText = (TextView) findViewById(R.id.bluetooth_status);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		
		if (mBluetoothAdapter == null) {
			bluetoothNotAvailable();
		} else {
			if (mBluetoothAdapter.isEnabled()) {
				bluetoothEnabled();
			} else {
				bluetoothDisabled();
			}
			mBluetoothStatusBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					boolean bluetoothOff = !mBluetoothAdapter.isEnabled();
					if (bluetoothOff) {
						Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivityForResult(enableBtIntent, 1);						
					} else {
						mBluetoothAdapter.disable();
						bluetoothDisabled();
						Toast.makeText(BluetoothEnableDisableActivity.this, "Bluetooth disabled", Toast.LENGTH_LONG).show();
					}
				}
			});
		}		
	}
	
	private void bluetoothNotAvailable() {
		mBluetoothStatusBtn.setImageResource(R.drawable.grey_button);
		mBluetoothStatusText.setText("Bluetooth is not available");
		mBluetoothStatusBtn.setEnabled(false);
	}
	
	private void bluetoothEnabled() {
		mBluetoothStatusBtn.setImageResource(R.drawable.green_button);
		mBluetoothStatusText.setText("Bluetooth is ON");
	}
	
	private void bluetoothDisabled() {
		mBluetoothStatusBtn.setImageResource(R.drawable.red_button);
		mBluetoothStatusText.setText("Bluetooth is OFF");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(this, "Bluetooth enabled", Toast.LENGTH_LONG).show();
				bluetoothEnabled();
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "User canceled", Toast.LENGTH_LONG).show();
			}
		}
	}

}

Bluetooth Availability

If getDefaultAdapter() returns null, then the device does not support Bluetooth in which case, we will update the image button to a grey bulb and set the bluetooth status to ‘Bluetooth is not available’.

	private void bluetoothNotAvailable() {
		mBluetoothStatusBtn.setImageResource(R.drawable.grey_button);
		mBluetoothStatusText.setText("Bluetooth is not available");
		mBluetoothStatusBtn.setEnabled(false);
	}

Turn on/Turn of bluetooth

We have added a listener to the bluetooth button to turn on or off when pressed. If the bluetooth is currently off then pressing the button will send a request to the system to enable it.
We will use an Intent object to communicate with the bluetooth service. To request that Bluetooth be enabled, we will call startActivityForResult() with the ACTION_REQUEST_ENABLE action Intent. This will issue a request to enable Bluetooth through the system settings.

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);

A dialog will appear requesting user permission to enable Bluetooth. If the user accepts, the system will begin to enable Bluetooth and focus will return to your application once the process completes (or fails).On completion of process, callback method onActivityResult() will be called. It will have the the request and response codes as the argument values.

We need to pass an integer (> 0) to startActivityForResult() so that onActivityResult() can compare the request code to know whether the reponse belongs to the same request.
If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or due to user clicking on 'deny') then the result code is RESULT_CANCELED..

Based on the result code, we will update the button's image and change the status.

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(this, "Bluetooth enabled", Toast.LENGTH_LONG).show();
				bluetoothEnabled();
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "User canceled", Toast.LENGTH_LONG).show();
			}
		}
	}

BluetoothAdapter.isEnabled() will let us know whether bluetooth is enabled.

Required bluetooth permissions

In order to use Bluetooth features in your application, you must declare the Bluetooth permission BLUETOOTH. Also we should add BLUETOOTH_ADMIN permission, in order to turn off the bluetooth.
Also note that if we have to add BLUETOOTH_ADMIN permission then BLUETOOTH permission is obligatory.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javarticles.android"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:maxSdkVersion="21"
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher_sandbox"
        android:label="@string/app_name" >
        <activity android:name=".BluetoothEnableDisableActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Run the Application

Initial Status Of Bluetooth. As you can see, it is off.

Bluetooth Initial Status

Bluetooth Initial Status

We will now turn it on by pressing the red button.

Turn on the Bluetooth

Turn on the Bluetooth

A dialog will appear requesting user permission to enable Bluetooth. We will accept it so that the system can begin to enable the bluetooth.

A dialog appears requesting user permission to enable Bluetooth

A dialog appears requesting user permission to enable Bluetooth

Focus will return to your application once the process completes (or fails).

Focus will return to your application once the process completes

Focus will return to your application once the process completes

Bluetooth is enabled.

Bluetooth is enabled

Bluetooth is enabled

Let's now turn it off.

Bluetooth disabled

Bluetooth disabled

Download the source code

In this article, I showed you how to enable/disable bluetooth. You can download the source code here: bluetoothEnableDisableExample.zip

Share.

Comments are closed.