Android Bluetooth Tutorial

Advertisements


Among many ways, Bluetooth is a way to send or recieve 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.

  1. Scan for other Bluetooth devices

  2. Get a list of paired devices

  3. Connect to other devices through service discovery

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.

private BluetoothAdapter BA;
BA = 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.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);       

Apart from this constant , ther are other constanst provided the API , that supports differnet tasks. They are listed below.

Sr.NoConstant & description
1ACTION_REQUEST_DISCOVERABLE
This constant is used for turn on discovering of bluetooth
2ACTION_STATE_CHANGED
This constant will notify that Bluetooth state has been changed
3ACTION_FOUND
This constant is used for recieving 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.

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

Apart form the pariredDevices , there are other methods in the API that gives more control over Blueetooth. THey are listed below.

Sr.NoMethod & description
1enable()
This method enables the adapter if not enabled
2isEnabled()
This method returns true if adapter is enabled
3disable()
This method disables the adapter
4getName()
This method returns the name of the Bluetooth adapter
5setName(String name)
This method changes the Bluetooth name
6getState()
This method returns the current state of the Bluetooth Adapter.
7startDiscovery()
This method starts the discovery process of the Bluetooth for 120 seconds.

Example

This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list of paired devices by the Bluetooth.

To experiment with this example , you need to run this on an actual device.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as AudioCapture under a package com.example.audiocapture. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add the code
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required.
4Modify res/values/string.xml file and add necessary string components.
5Modify AndroidManifest.xml to add necessary permissions.
6Run the application and choose a running android device and install the application on it and verify the results.

Here is the content of src/com.example.bluetooth/MainActivity.java

package com.example.bluetooth;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private Button On,Off,Visible,list;
   private BluetoothAdapter BA;
   private Set<BluetoothDevice>pairedDevices;
   private ListView lv;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      On = (Button)findViewById(R.id.button1);
      Off = (Button)findViewById(R.id.button2);
      Visible = (Button)findViewById(R.id.button3);
      list = (Button)findViewById(R.id.button4);

      lv = (ListView)findViewById(R.id.listView1);

      BA = BluetoothAdapter.getDefaultAdapter();
   }

   public void on(View view){
      if (!BA.isEnabled()) {
         Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOn, 0);
         Toast.makeText(getApplicationContext(),"Turned on" 
         ,Toast.LENGTH_LONG).show();
      }
      else{
         Toast.makeText(getApplicationContext(),"Already on",
         Toast.LENGTH_LONG).show();
         }
   }
   public void list(View view){
      pairedDevices = BA.getBondedDevices();

      ArrayList list = new ArrayList();
      for(BluetoothDevice bt : pairedDevices)
         list.add(bt.getName());

      Toast.makeText(getApplicationContext(),"Showing Paired Devices",
      Toast.LENGTH_SHORT).show();
      final ArrayAdapter adapter = new ArrayAdapter
      (this,android.R.layout.simple_list_item_1, list);
      lv.setAdapter(adapter);

   }
   public void off(View view){
      BA.disable();
      Toast.makeText(getApplicationContext(),"Turned off" ,
      Toast.LENGTH_LONG).show();
   }
   public void visible(View view){
      Intent getVisible = new Intent(BluetoothAdapter.
      ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible, 0);

   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

Here is the content of activity_main.xml

<RelativeLayout xmlns: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" >

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentTop="true" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/app_name"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="on"
      android:text="@string/on" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="visible"
      android:text="@string/Visible" />

   <Button
      android:id="@+id/button3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="list"
      android:text="@string/List" />

   <Button
      android:id="@+id/button4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="off"
      android:text="@string/off" />

   <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:visibility="visible" >

   </ListView>

   </LinearLayout>
</ScrollView>

</RelativeLayout>

Here is the content of Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Bluetooth</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="on">Turn On</string>
   <string name="off">Turn Off</string>
   <string name="Visible">Get Visible</string>
   <string name="List">List Devices</string>

</resources>

Here is the content of AndroidManifest.xml

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

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <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.example.bluetooth.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>

Let's try to run your AndroidCapture application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid Bluetooth Tutorial

Select your mobile device as an option and then check your mobile device which will display following screen:

Anroid Bluetooth Tutorial

Now select Turn On to turn on the bluetooth. But as you select it , your Bluetooth will not be turned on. Infact , it will ask your permission to enable the Bluetooth.

Anroid Bluetooth Tutorial

Now just select the Get Visible button to turn on your visibiltiy. The following screen would appear asking your permission to turn on discovery for 120 seconds.

Anroid Bluetooth Tutorial

Now just select the List Devices option. It will list down the paired devices in the list view. In my case , i have only one paired device. It is shown below.

Anroid Bluetooth Tutorial

Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you swithc off the bluetooth indicating the successfull swithching off of Bluetooth.

Anroid Bluetooth Tutorial

Advertisements
Advertisements