Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.
Android provides Bluetooth API to perform these different operations.
Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below –
1 2 |
private BluetoothAdapter bluetoothAdapter; bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); |
In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is –
1 2 |
Intent intent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 111); |
Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below –
Constant | Description |
---|---|
ACTION_REQUEST_DISCOVERABLE | This constant is used for turn on discovering of bluetooth. |
ACTION_STATE_CHANGED | This constant will notify that Bluetooth state has been changed. |
ACTION_FOUND | This constant is used for receiving information about each device that is discovered. |
Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of Bluetooth devices. Its syntax is –
1 2 |
private Set<BluetoothDevice> pairedDevices; pairedDevices = bluetoothAdapter.getBondedDevices(); |
Apart form the paired Devices , there are other methods in the API that gives more control over Bluetooth. They are listed below –
Method | Description |
---|---|
enable() | This method enables the adapter if not enabled. |
isEnabled() | This method returns true if adapter is enabled. |
disable() | This method disables the adapter. |
getName() | This method returns the name of the Bluetooth adapter. |
setName(String name) | This method changes the Bluetooth name. |
getState() | This method returns the current state of the Bluetooth Adapter. |
startDiscovery() | This method starts the discovery process of the Bluetooth for 120 seconds. |
In this tutorial, we are going to learn how to Enable, Disable, Enable Discovery, search nearby Bluetooth devices and Pair with other Bluetooth devices.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Bluetooth Demo</string> <string name="turn_on">Turn On</string> <string name="turn_off">Turn Off</string> <string name="make_visible">Visible</string> <string name="list_paired_devices">List Paired Devices</string> <string name="search_new_devices">Search New Devices</string> <string name="cancel">Cancel</string> </resources> |
3. To work on Bluetooth we have to give certain permission in Manifest file and add this line to your manifest.
1 2 3 |
<!-- Uses permission required to use bluetooth --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.bluetooth_demo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- Uses permission required to use bluetooth --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.bluetooth_demo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
4. Now, create a xml layout naming activity_main.xml. In this layout i put some buttons to work on Bluetooth and a ListView to show paired and new searched devices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <TextView android:id="@+id/bluetooth_status" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:textColor="#000000" android:textSize="17sp" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:orientation="horizontal" > <Button android:id="@+id/turnOn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/turn_on" /> <Button android:id="@+id/turnOff" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/turn_off" /> <Button android:id="@+id/make_visible" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/make_visible" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal" > <Button android:id="@+id/show_paired_devices" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/list_paired_devices" /> <Button android:id="@+id/search_new_devices" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/search_new_devices" /> </LinearLayout> <ListView android:id="@+id/list_devices" android:layout_width="fill_parent" android:layout_height="fill_parent" > </ListView> </LinearLayout> |
5. We will display Bluetooth device name with device MAC address. So I am using custom listview for that. This is customview.xml i.e custom layout.
If you are new to Custom ListView then refer this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="4dp" android:layout_marginTop="4dp" > <TextView android:id="@+id/devices_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" android:textColor="#000000" android:textSize="15sp" /> </LinearLayout> |
6. For pairing two Bluetooth devices I am using this Thread class. This class can be used to pair any bluetooth devices. Here BluetoothSocket is used to pair devices by connect() method. Before connecting we have to unregister all broadcast receivers and bluetooth discovery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// This thread will do task for pairing devices private class ConnectThread extends Thread { private BluetoothSocket mmSocket; // Bluetooth Socket private final BluetoothDevice mmDevice; private final UUID MY_UUID = UUID .fromString("00001101-0000-1000-8000-00805f9b34fb"); // This is // Unique // Id // for // your // device public ConnectThread(BluetoothDevice device) { BluetoothSocket tmp = null; mmDevice = device; try { // This methods are used to make pairing tmp = device.createRfcommSocketToServiceRecord(MY_UUID); Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); tmp = (BluetoothSocket) m.invoke(device, 1); } catch (Exception e) { e.printStackTrace(); } mmSocket = tmp; } public void run() { // Cancelling discovery is neccessary bluetooth_adapter.cancelDiscovery();// If bluetooth adapter is // already discovering then // cancel it try { // Also unregister receiver unregisterReceiver(reciever); } catch (IllegalArgumentException e) { e.printStackTrace(); } try { mmSocket.connect();// Pair device Log.e(TAG, "Connection Establish"); // Via this Log you can // check the connection // status } catch (IOException connectException) { connectException.printStackTrace(); try { mmSocket.close(); // If exception occurs close Socket Log.e(TAG, "Connection Failed"); } catch (IOException closeException) { closeException.printStackTrace(); } return; } } // On cancel display Log and close socket public void cancel() { try { Log.e(TAG, "Connection Failed on cancel"); mmSocket.close(); } catch (IOException e) { } } } |
7. Finally come to your MainActivity.java and add the following code. In this java class i used above discussed methods of Bluetooth to work over Bluetooth and a Thread class to pair devices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
package com.bluetooth_demo; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Set; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements OnClickListener, OnItemClickListener { private static final int Request_enable_Bt = 1; // Varaible for Activtiy // result method private static Button turn_on, turn_off, paired_devices, search_devices, make_visible; private static TextView bluetooth_status; private static ListView list_devices; private static ArrayList<BluetoothDevice> bluetoothDevice_List; private static CustomAdapter BtArrayAdapter; private static final String TAG = MainActivity.class.getSimpleName();// TAG // for // logs // Bluetooth Variables private static BluetoothAdapter bluetooth_adapter; private static Set<BluetoothDevice> pairedDevices; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); checkBluetoothAdapter();// Check Bluetooth presence } // Initialize the views private void init() { turn_on = (Button) findViewById(R.id.turnOn); turn_off = (Button) findViewById(R.id.turnOff); paired_devices = (Button) findViewById(R.id.show_paired_devices); search_devices = (Button) findViewById(R.id.search_new_devices); make_visible = (Button) findViewById(R.id.make_visible); list_devices = (ListView) findViewById(R.id.list_devices); bluetooth_status = (TextView) findViewById(R.id.bluetooth_status); } // Check if bluetooth is present or not private void checkBluetoothAdapter() { bluetooth_adapter = BluetoothAdapter.getDefaultAdapter(); if (bluetooth_adapter == null) { // If bluetooth doesn't present disable all buttons and display a // toast disableButtons(); Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth.", Toast.LENGTH_LONG).show(); } else { // If bluetooth is there then check if it is ON or not for status if (bluetooth_adapter.isEnabled()) { bluetooth_status.setText("Status: Bluetooth Enabled."); } else { bluetooth_status.setText("Status: Bluetooth Disabled."); } setListeners();// Set listeners } } // Disable all buttons private void disableButtons() { turn_on.setEnabled(false); turn_off.setEnabled(false); paired_devices.setEnabled(false); search_devices.setEnabled(false); make_visible.setEnabled(false); bluetooth_status.setText("Status: - Bluetooth Not supported"); } // Set click listeners private void setListeners() { turn_on.setOnClickListener(this); turn_off.setOnClickListener(this); make_visible.setOnClickListener(this); paired_devices.setOnClickListener(this); search_devices.setOnClickListener(this); list_devices.setOnItemClickListener(this); } // On button clicks call there representative methods @Override public void onClick(View v) { switch (v.getId()) { case R.id.turnOn: turnOn(); break; case R.id.turnOff: turnOff(); break; case R.id.make_visible: makeBluetoothVisible(); break; case R.id.show_paired_devices: showPairedDevices(); break; case R.id.search_new_devices: searchNewDevices(); break; } } // Turn bluetooth ON private void turnOn() { boolean isBluetoothEnabled = isBluetoothEnabled();// Bluetooth enabled // or disabled if (!isBluetoothEnabled) { // If disabled Switch On bluetooth Intent in = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(in, Request_enable_Bt); } else { // If it is already On then display a toast Toast.makeText(getApplicationContext(), "Bluetooth is already on", Toast.LENGTH_SHORT).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // On Activity result check the response code with send code if (requestCode == Request_enable_Bt) { // If bluetooth enabled/disabled then change status if (bluetooth_adapter.isEnabled()) { Toast.makeText(getApplicationContext(), "Bluetooth turned on", Toast.LENGTH_SHORT).show(); bluetooth_status.setText("Status: Bluetooth Enabled."); } else { bluetooth_status.setText("Status: Bluetooth Disabled."); Toast.makeText(getApplicationContext(), "Bluetooth enabling cancelled.", Toast.LENGTH_SHORT) .show(); } } super.onActivityResult(requestCode, resultCode, data); } // Show paired devices private void showPairedDevices() { boolean isBluetoothEnabled = isBluetoothEnabled();// Before shwoing // devices check if // bluetooth is on // or off if (isBluetoothEnabled) { pairedDevices = bluetooth_adapter.getBondedDevices();// Get bonded // devices // via this // method bluetoothDevice_List = new ArrayList<BluetoothDevice>(); for (BluetoothDevice device : pairedDevices) bluetoothDevice_List.add(device);// Add bonded devices to // arrayList BtArrayAdapter = new CustomAdapter(MainActivity.this, R.layout.customview, bluetoothDevice_List);// set adapter list_devices.setAdapter(BtArrayAdapter);// Set adapter over listview BtArrayAdapter.notifyDataSetChanged();// notify adapter } } // Search new Bluetooth Devices private void searchNewDevices() { boolean isBluetoothEnabled = isBluetoothEnabled();// If bluetooth is // enabled then // proceed further if (isBluetoothEnabled) { if (bluetooth_adapter.isDiscovering()) {// Check if bluetooth // adapter is already // discovering or not bluetooth_adapter.cancelDiscovery();// If already discovering // then cancel discovery search_devices.setText(R.string.search_new_devices);// Change // button // text } else { search_devices.setText(R.string.cancel);// If not discovering // then change button // text bluetooth_adapter.startDiscovery();// and start discovering // devices registerReceiver(reciever, new IntentFilter( BluetoothDevice.ACTION_FOUND));// Register broadcast // receiver for New // Device found } } } // Broadcast Receiver for New Device Found final BroadcastReceiver reciever = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction();// Get Sent Action if (BluetoothDevice.ACTION_FOUND.equals(action)) {// Check if sent // action is // equal to // device action BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// Get // new // Device // add the name and the MAC address of the object to the // arrayAdapter // If it's already paired, skip it, because it's been listed // already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { bluetoothDevice_List = new ArrayList<BluetoothDevice>(); bluetoothDevice_List.add(device); BtArrayAdapter = new CustomAdapter(MainActivity.this, R.layout.customview, bluetoothDevice_List); list_devices.setAdapter(BtArrayAdapter); BtArrayAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "Device found.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "No Devices found.", Toast.LENGTH_SHORT).show(); } search_devices.setText(R.string.search_new_devices);// Change // button // text // after // searching // devices } // Other Actions of Bluetooth devices else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) { // Device is now connected } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED .equals(action)) { // Done searching } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED .equals(action)) { // Device is about to disconnect } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { // Device has disconnected } } }; // Make device discoverable private void makeBluetoothVisible() { boolean isBluetoothEnabled = isBluetoothEnabled(); if (isBluetoothEnabled) { Intent in = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); in.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);// Make // device // discoverable // for // 300sec startActivity(in); } } private void turnOff() { boolean isBluetoothEnabled = isBluetoothEnabled(); if (isBluetoothEnabled) { bluetooth_adapter.disable(); // Switch off bluetooth bluetooth_status.setText("Status: Bluetooth Disabled."); // Change // status // text Toast.makeText(getApplicationContext(), "Bluetooth turned off", Toast.LENGTH_SHORT).show(); } } // Method that return boolean value about device enabled or disabled private boolean isBluetoothEnabled() { if (!bluetooth_adapter.isEnabled()) { Toast.makeText(MainActivity.this, "Bluetooth is disabled. Please turn on first.", Toast.LENGTH_SHORT).show(); return false; // if device is disabled } return true;// If device is enabled } // On listview item clicked @Override public void onItemClick(AdapterView<> parent, View view, int position, long id) { boolean isBluetoothEnabled = isBluetoothEnabled();// Before doing // anything check if // bluetooth is on // or off if (isBluetoothEnabled) {// If bluetooth ON // then check if selected device is already paired or not if (bluetoothDevice_List.get(position).getBondState() != BluetoothDevice.BOND_BONDED) { // If device not paired then start the thread to pair devices ConnectThread mConnectedThread = new ConnectThread( bluetoothDevice_List.get(position)); mConnectedThread.start(); } else { // else show a toast Toast.makeText(getApplicationContext(), "Already paired.", Toast.LENGTH_SHORT).show(); } } } // This thread will do task for pairing devices private class ConnectThread extends Thread { private BluetoothSocket mmSocket; // Bluetooth Socket private final BluetoothDevice mmDevice; private final UUID MY_UUID = UUID .fromString("00001101-0000-1000-8000-00805f9b34fb"); // This is // Unique // Id // for // your // device public ConnectThread(BluetoothDevice device) { BluetoothSocket tmp = null; mmDevice = device; try { // This methods are used to make pairing tmp = device.createRfcommSocketToServiceRecord(MY_UUID); Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class }); tmp = (BluetoothSocket) m.invoke(device, 1); } catch (Exception e) { e.printStackTrace(); } mmSocket = tmp; } public void run() { // Cancelling discovery is neccessary bluetooth_adapter.cancelDiscovery();// If bluetooth adapter is // already discovering then // cancel it try { // Also unregister receiver unregisterReceiver(reciever); } catch (IllegalArgumentException e) { e.printStackTrace(); } try { mmSocket.connect();// Pair device Log.e(TAG, "Connection Establish"); // Via this Log you can // check the connection // status } catch (IOException connectException) { connectException.printStackTrace(); try { mmSocket.close(); // If exception occurs close Socket Log.e(TAG, "Connection Failed"); } catch (IOException closeException) { closeException.printStackTrace(); } return; } } // On cancel display Log and close socket public void cancel() { try { Log.e(TAG, "Connection Failed on cancel"); mmSocket.close(); } catch (IOException e) { } } } // On destroy unregister receiver @Override protected void onDestroy() { super.onDestroy(); // Try catch block is used because receiver can throw exception if // receiver not registered try { unregisterReceiver(reciever); } catch (IllegalArgumentException e) { e.printStackTrace(); } } // Custom Adapter class for Custom ListView Items private class CustomAdapter extends ArrayAdapter<BluetoothDevice> { private Context context; private int resource; private ArrayList<BluetoothDevice> deviceName; public CustomAdapter(Context context, int resource, ArrayList<BluetoothDevice> deviceName) { super(context, resource); this.context = context; this.resource = resource; this.deviceName = deviceName; } @Override public int getCount() { return deviceName.size();// Array List size } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(resource, parent, false); // Inflate // layout TextView deviceName = (TextView) convertView .findViewById(R.id.devices_name);// Find textView id // Set device name and device address over textview deviceName.setText(this.deviceName.get(position).getName() + "n" + this.deviceName.get(position).getAddress()); } return convertView; } } } |
8. Now, you are all done, run your app and you will get the output as shown in the video.
Thanks.
Subscribe to us and get the latest news.