Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Enabling Bluetooth and Making the Device Discoverable

Author: Rachee Singh
Published? true
FormatLanguage: WikiFormat

Problem:

If the application requires the Bluetooth adapter to be switched On, the programmer needs to check if its enabled. If it is not, the use should be prompted to enable Bluetooth. For allowing remote devices to detect the host device, the host device should be made discoverable.

Solution:

Use of Intents to prompt the user to enable Bluetooth and make the device discoverable.

Discussion:

Before permorming any action with an instance of BluetoothAdapter class, it should be checked if the device had enabled the Bluetooth adapter using the isEnabled() method. If it returns false then the user should be prompted to enable Bluetooth.


BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();
if (!BT.isEnabled()) {
//Taking user's permission to switch the bluetooth adapter On. 
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} 

This piece of code would show an AlertDialog to the user prompting her to enable Bluetooth.

On returning to the activity that started the intent, onActivityResult() is called in which, the name of the host device and its MAC address can be extracted.


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if(requestCode==REQUEST_ENABLE_BT && resultCode==Activity.RESULT_OK) {
                BluetoothAdapter BT = BluetoothAdapter.getDefaultAdapter();
		String address = BT.getAddress();
        	String name = BT.getName();
        	String toastText = name + " : " + address;
        	Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
}

In order to make the device discoverable to other Bluetooth-enabled devices in the vicinity, these lines of code can be used to prompt take the user's permission.


//Taking user's permission to make the device discoverable for 120 secs.
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(discoverableIntent);

No records found.