Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Bluetooth Tutorial


Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to perform several tasks such as:

  • scan bluetooth devices
  • connect and transfer data from and to other devices
  • manage multiple connections etc.

Android Bluetooth API

The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:

  • BluetoothAdapter
  • BluetoothDevice
  • BluetoothSocket
  • BluetoothServerSocket
  • BluetoothClass
  • BluetoothProfile
  • BluetoothProfile.ServiceListener
  • BluetoothHeadset
  • BluetoothA2dp
  • BluetoothHealth
  • BluetoothHealthCallback
  • BluetoothHealthAppConfiguration

BluetoothAdapter class

By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:

  • String ACTION_REQUEST_ENABLE
  • String ACTION_REQUEST_DISCOVERABLE
  • String ACTION_DISCOVERY_STARTED
  • String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:

  • static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of BluetoothAdapter.
  • boolean enable() enables the bluetooth adapter if it is disabled.
  • boolean isEnabled() returns true if the bluetooth adapter is enabled.
  • boolean disable() disables the bluetooth adapter if it is enabled.
  • String getName() returns the name of the bluetooth adapter.
  • boolean setName(String name) changes the bluetooth name.
  • int getState() returns the current state of the local bluetooth adapter.
  • Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded) BluetoothDevice objects.
  • boolean startDiscovery() starts the discovery process.

Android Bluetooth Example: enable, disable and make discovrable bluetooth programmatically

You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml
  1. <RelativeLayout xmlns:androclass=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     tools:context=“.MainActivity” >
  6.     <TextView android:text=“”
  7.      android:id=“@+id/out”
  8.      android:layout_width=“wrap_content”
  9.      android:layout_height=“wrap_content”>
  10.     </TextView>
  11.     <Button
  12.         android:id=“@+id/button1”
  13.         android:layout_width=“wrap_content”
  14.         android:layout_height=“wrap_content”
  15.         android:layout_alignParentLeft=“true”
  16.         android:layout_alignParentTop=“true”
  17.         android:layout_marginLeft=“30dp”
  18.         android:layout_marginTop=“49dp”
  19.         android:text=“TURN_ON” />
  20.     <Button
  21.         android:id=“@+id/button2”
  22.         android:layout_width=“wrap_content”
  23.         android:layout_height=“wrap_content”
  24.         android:layout_alignLeft=“@+id/button1”
  25.         android:layout_below=“@+id/button1”
  26.         android:layout_marginTop=“27dp”
  27.         android:text=“DISCOVERABLE” />
  28.     <Button
  29.         android:id=“@+id/button3”
  30.         android:layout_width=“wrap_content”
  31.         android:layout_height=“wrap_content”
  32.         android:layout_alignLeft=“@+id/button2”
  33.         android:layout_below=“@+id/button2”
  34.         android:layout_marginTop=“28dp”
  35.         android:text=“TURN_OFF” />
  36. </RelativeLayout>

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

  1. <uses-permission android:name=“android.permission.BLUETOOTH” />
  2. <uses-permission android:name=“android.permission.BLUETOOTH_ADMIN” />

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml
  1. <?xml version=“1.0” encoding=“utf-8”?>
  2. <manifest xmlns:androclass=“http://schemas.android.com/apk/res/android”
  3.     package=“com.example.bluetooth”
  4.     android:versionCode=“1”
  5.     android:versionName=“1.0” >
  6.     <uses-sdk
  7.         android:minSdkVersion=“8”
  8.         android:targetSdkVersion=“16” />
  9.     <uses-permission android:name=“android.permission.BLUETOOTH” />
  10.     <uses-permission android:name=“android.permission.BLUETOOTH_ADMIN” />
  11.     <application
  12.         android:allowBackup=“true”
  13.         android:icon=“@drawable/ic_launcher”
  14.         android:label=“@string/app_name”
  15.         android:theme=“@style/AppTheme” >
  16.         <activity
  17.             android:name=“com.example.bluetooth.MainActivity”
  18.             android:label=“@string/app_name” >
  19.             <intent-filter>
  20.                 <action android:name=“android.intent.action.MAIN” />
  21.                 <category android:name=“android.intent.category.LAUNCHER” />
  22.             </intent-filter>
  23.         </activity>
  24.     </application>
  25. </manifest>

Activity class

Let’s write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java
  1. package com.example.bluetooth;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.view.Menu;
  5. import android.app.Activity;
  6. import android.bluetooth.BluetoothAdapter;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.View;
  12. import android.widget.Button;
  13. import android.widget.TextView;
  14. import android.widget.Toast;
  15. public class MainActivity extends Activity {
  16.       private static final int REQUEST_ENABLE_BT = 0;
  17.       private static final int REQUEST_DISCOVERABLE_BT = 0;
  18.     @Override
  19.     protected void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.activity_main);
  22.     final TextView out=(TextView)findViewById(R.id.out);
  23.     final Button button1 = (Button) findViewById(R.id.button1);
  24.     final Button button2 = (Button) findViewById(R.id.button2);
  25.     final Button button3 = (Button) findViewById(R.id.button3);
  26.     final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  27.     if (mBluetoothAdapter == null) {
  28.        out.append(“device not supported”);
  29.     }
  30.     button1.setOnClickListener(new View.OnClickListener() {
  31.         public void onClick(View v) {
  32.             if (!mBluetoothAdapter.isEnabled()) {
  33.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  34.                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  35.             }
  36.         }
  37.     });
  38.     button2.setOnClickListener(new View.OnClickListener() {
  39.      @Override
  40.         public void onClick(View arg0) {
  41.             if (!mBluetoothAdapter.isDiscovering()) {
  42.                   //out.append(“MAKING YOUR DEVICE DISCOVERABLE”);
  43.                    Toast.makeText(getApplicationContext(), “MAKING YOUR DEVICE DISCOVERABLE”,
  44.              Toast.LENGTH_LONG);
  45.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  46.                 startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
  47.             }
  48.         }
  49.     });
  50.     button3.setOnClickListener(new View.OnClickListener() {
  51.         @Override
  52.         public void onClick(View arg0) {
  53.             mBluetoothAdapter.disable();
  54.             //out.append(“TURN_OFF BLUETOOTH”);
  55.             Toast.makeText(getApplicationContext(), “TURNING_OFF BLUETOOTH”, Toast.LENGTH_LONG);
  56.             }
  57.     });
  58. }
  59.     @Override
  60.     public boolean onCreateOptionsMenu(Menu menu) {
  61.         // Inflate the menu; this adds items to the action bar if it is present.
  62.         getMenuInflater().inflate(R.menu.activity_main, menu);
  63.         return true;
  64.     }
  65. }

download this android example

You need to run it on the real device (e.g. mobile) to test the application.


Next topics of android bluetooth tutorial:

android bluetooth list paired devices example

Comments

comments