Android Bluetooth

Describe Bluetooth API in android and its process to enable Bluetooth.

Android supports for the Bluetooth, which means it allows a device to exchange data with other Bluetooth devices without being connected to each other with any wire. Android Bluetooth APIs enable you to connect to other Bluetooth devices wirelessly.

Android application can perform the following task by using Bluetooth:
  • Turn on, Turn off Bluetooth.
  • Paired or available devices in the local area.
  • Transferring data between devices.
  • Connecting devices.
Process for enabling Bluetooth:
  • BluetoothAdapter class is the main class while working with Bluetooth. This class helps you discover other Bluetooth devices.
  • Create an object of BluetoothAdapter class by calling the static method getDefaultAdapter().
Its syntax is given below:
BluetoothAdapterB_adapter;
B_adapter = BluetoothAdapter.getDefaultAdapter();

If getDefaultAdapter() method returns null, then the device does not support Bluetooth.
if (B_adapter == null)
{
     // Your device does not support Bluetooth
}

isEnabled() method is used to check whether Bluetooth is currently enabled or not. Its return type is Boolean. If this method returns false, then Bluetooth is disabled. To enable Bluetooth, call startActivityForResult() method with the ACTION_REQUEST_ENABLE action Intent.

Its syntax is given below.
if (! B_adapter.isEnabled())
{
     Intent intent = newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
     startActivityForResult (intent, 1);
}

The above code is requesting user permission to enable Bluetooth. If everything is fine, then your activity receives the RESULT_OK result code in the onActivityResult(). If enabling Bluetooth is not succeeded, then the result code is RESULT_CANCELED. Apart from ACTION_REQUEST_ENABLE constant, there are other important constants which are used to support different tasks.
  • ACTION_REQUEST_DISCOVERABLE
  • ACTION_STATE_CHANGED
  • ACTION_FOUND
To find out the paired devices through Bluetooth, use getBondedDevices() method of BluetoothAdapter class.

Its syntax is given below:
Set<BluetoothDevice>pairedDevices = B_adapter.getBondedDevices();

Modify AndroidManifest.xml to add necessary permissions as follows:
<uses-permissionandroid:name = "android.permission.BLUETOOTH"/>
<uses-permissionandroid:name = "android.permission.BLUETOOTH_ADMIN"/>"

Give example to enable Bluetooth and find out paired devices.

Following is the content of res/layout/activity_main.xml file:

All of the Bluetooth APIs are available in the android.bluetooth package.
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:paddingBottom = "@dimen/activity_vertical_margin"
android:paddingLeft = "@dimen/activity_horizontal_margin"
android:paddingRight = "@dimen/activity_horizontal_margin"
android:paddingTop = "@dimen/activity_vertical_margin"
tools:context = ".MainActivity">

<Button
android:id = "@+id/btnON"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentLeft = "true"
android:layout_alignParentTop = "true"
android:layout_marginLeft = "20dp"
android:layout_marginTop = "32dp"
android:text = "Turn ON"/>

<Button
android:id = "@+id/btnOFF"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/btnON"
android:layout_alignRight = "@+id/btnON"
android:layout_below = "@+id/btnON"
android:text = "Turn OFF"/>

<Button
android:id = "@+id/btnPairDevice"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/btnOFF"
android:layout_alignRight = "@+id/btnOFF"
android:layout_below = "@+id/btnOFF"
android:text = "Paired Device"/>

<ListView
android:id = "@+id/listView1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_alignLeft = "@+id/btnPairDevice"
android:layout_below = "@+id/btnPairDevice">
</ListView>

</RelativeLayout>

Following is the content of the modified MainActivity.java file
publicclassMainActivityextends Activity implementsOnClickListener
{
     BluetoothAdapterB_adapter;
     Button on,off,conDevice;
     Set<BluetoothDevice>pairedDevices;
     ListViewlv;
     @Override
     protectedvoidonCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          on = (Button)findViewById(R.id.btnON);
          off = (Button)findViewById(R.id.btnOFF);
          conDevice = (Button)findViewById(R.id.btnPairDevice);
          on.setOnClickListener(this);
          off.setOnClickListener(this);
          conDevice.setOnClickListener(this);
          lv = (ListView)findViewById(R.id.listView1);
          B_adapter = BluetoothAdapter.getDefaultAdapter();
     }
     @Override
     publicvoidonClick(View v)
     {
          // TODO Auto-generated method stub
          switch(v.getId())
          {
               caseR.id.btnON :
                    TurnOn();
                    break;
               caseR.id.btnOFF:
                    TurnOff();
                    break;
               caseR.id.btnPairDevice :
                    connectedDevice();
                    break;
          }
     }
     publicvoidTurnOn()
     {
          if (!B_adapter.isEnabled())
          {
               Intent intent = newIntent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
               startActivityForResult(intent, 1);
               Toast.makeText (getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();
          }
          else
          {
               Toast.makeText (getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_LONG).show();
          }
     }
     publicvoidTurnOff()
     {
          B_adapter.disable();
          Toast.makeText(getApplicationContext(),"Turned off",Toast.LENGTH_LONG).show();
     }
     publicvoidconnectedDevice()
     {
          pairedDevices = B_adapter.getBondedDevices();
          ArrayList list = newArrayList();
          for(BluetoothDevicebt : pairedDevices)
          list.add(bt.getName());
          Toast.makeText(getApplicationContext(),"Showing Paired Devices",Toast.LENGTH_SHORT).show();
          ArrayAdapter adapter = newArrayAdapter (this,android.R.layout.simple_list_item_1, list);
          lv.setAdapter(adapter);
     }
}

Following is the content of the modified AndroidManifest.xml file
<?xmlversion = "1.0"encoding = "utf-8"?>
<manifestxmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.bluetooth_test"
android:versionCode = "1"
android:versionName = "1.0">

<uses-sdk
android:minSdkVersion = "8"
android:targetSdkVersion = "18"/>
<uses-permissionandroid:name = "android.permission.BLUETOOTH"/>
<uses-permissionandroid: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.example.bluetooth_test.MainActivity"
android:label = "@string/app_name">
<intent-filter>
<actionandroid:name = "android.intent.action.MAIN"/>

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

</manifest>

Bluetooth App
Note: Please run the above program in real device not in android virtual device.