Home » Android » core » Bluetooth » BluetoothAdapter » Android Bluetooth Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Android Bluetooth Example

If we want to exchange data between different devices through our application, Bluetooth is a way for wirelessly connection between devices that support Bluetooth. Android system provides us Bluetooth APIs, from which we can:

  • Find paired Bluetooth devices
  • Search for other Bluetooth devices
  • Connect to one or more of these devices
  • Receive and Transfer data

In our example we are going to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices.

 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SDK 4.4

1. Create a New Android Application Project

Open Eclipse IDE and go to File → New → Project → Android Application Project.

Specify the name of the application, the project and the package and then click Next.

BluetoothTestProj1

In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.

BluetoothTestProj2

In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

createProject3!

Choose the “Blank Activity” option and press Next.

createProject4!

Specify the name of the new Activity and the name of the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. Finally, press Finish.

createProject5!

Now that the project is created, you can see the final structure of the project in the image below.

BluetoothTestProjStructure

2. Create the layout of the Main Activity

As we mentioned, our app will do three basic functions. We will add two Buttons in order to enable and disable Bluetooth. Moreover we will put two Buttons, one for the paired and the other for the enabled Bluetooth devices. Also to show the Bluetooth devices in each situation, we will add a ListView.

Open res/layout/activity_main.xml and go to the respective xml tab. Then paste the code below.

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"
   tools:context=".MainActivity" >

  <TextView
       android:id="@+id/text"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textAppearance="?android:attr/textAppearanceLarge"
       android:text="@string/Text" />
     
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="horizontal"
      android:layout_marginTop="30dp" >

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

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

   </LinearLayout>
   
   
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:layout_marginTop="80dp" >
   
	   <Button
	      android:id="@+id/paired"
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:text="@string/List" />
	     
	   <Button
	      android:id="@+id/search"
	      android:layout_width="wrap_content"
	      android:layout_height="wrap_content"
	      android:text="@string/Find" />

	   <ListView
	       android:id="@+id/listView1"
	       android:layout_width="fill_parent"
	       android:layout_height="200dp" >
	
	   </ListView>

   </LinearLayout>

</RelativeLayout>

Also, we have to specify the texts in the stings.xml file, so go to res/values/strings.xml and specifically to the xml tab. Then paste the following.

strings.xml:

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

    <string name="app_name">BluetoothTest</string>
    <string name="action_settings">Settings</string>
    <string name="Text">Status: -</string>
    <string name="on">Turn On</string>
    <string name="off">Turn Off</string>
    <string name="List">List paired Devices</string>
    <string name="Find">Search new Devices / Cancel</string>

</resources>

3. Code the Main Activity

To interact with Bluetooth, BluetoothAdapter class should be used, so getDefaultAdapter() is called to take an instance of this object class. To turn on Bluetooth, firstly we should check if BluetoothAdapter is already enabled. If not, startActivityForResult() method with the ACTION_REQUEST_ENABLE action Intent is called. Notice that the second parameter of startActivityForResult() method, is an integer and is set greater than 0, so the system goes back to our implementation of onActivityResult() method of the Activity. In contrast, we call disable() method in order to turn off Bluetooth.

A very important functionality in Bluetooth, is to scan and search for devices that are discoverable and can be accessed in a local area. When we say discoverable, we mean that a device is enabled and its information is shared and visible. Before the discovering procedure it is good to query the set of paired devices, because the desirable device may be already known. Paired devices are previously connected devices, where the information is stored and reused by the Bluetooth APIs. To set the paired devices, getBondedDevices() is called, so we can find out all the BluetoothDevices.

For the performance of device discovery, we call startDiscovery() method. To receive all the information of the BluetoothDevices that are discovered, we should register a BroadcastReceiver for the Intent with ACTION_FOUND. It is recommended to cancel the discovery procedure because BluetoothAdapter consumes many resources, so cancelDiscovery()  is used for this reason. Also in our example, we unregister the previously registered BroadcastReceiver and remove all its filters, by calling unregisterReceiver() in the onDestroy() method of our Activity.

Open src/com.javacodegeeks.android.bluetoothtest/MainActivity.java file and paste the following code.

MainActivity.java:

package com.javacodegeeks.android.bluetoothtest;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private static final int REQUEST_ENABLE_BT = 1;
   private Button onBtn;
   private Button offBtn;
   private Button listBtn;
   private Button findBtn;
   private TextView text;
   private BluetoothAdapter myBluetoothAdapter;
   private Set<BluetoothDevice> pairedDevices;
   private ListView myListView;
   private ArrayAdapter<String> BTArrayAdapter;
  
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      // take an instance of BluetoothAdapter - Bluetooth radio
      myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if(myBluetoothAdapter == null) {
    	  onBtn.setEnabled(false);
    	  offBtn.setEnabled(false);
    	  listBtn.setEnabled(false);
    	  findBtn.setEnabled(false);
    	  text.setText("Status: not supported");
    	  
    	  Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
         		 Toast.LENGTH_LONG).show();
      } else {
	      text = (TextView) findViewById(R.id.text);
	      onBtn = (Button)findViewById(R.id.turnOn);
	      onBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				on(v);
			}
	      });
	      
	      offBtn = (Button)findViewById(R.id.turnOff);
	      offBtn.setOnClickListener(new OnClickListener() {
	  		
	  		@Override
	  		public void onClick(View v) {
	  			// TODO Auto-generated method stub
	  			off(v);
	  		}
	      });
	      
	      listBtn = (Button)findViewById(R.id.paired);
	      listBtn.setOnClickListener(new OnClickListener() {
	  		
	  		@Override
	  		public void onClick(View v) {
	  			// TODO Auto-generated method stub
	  			list(v);
	  		}
	      });
	      
	      findBtn = (Button)findViewById(R.id.search);
	      findBtn.setOnClickListener(new OnClickListener() {
	  		
	  		@Override
	  		public void onClick(View v) {
	  			// TODO Auto-generated method stub
	  			find(v);
	  		}
	      });
	    
	      myListView = (ListView)findViewById(R.id.listView1);
	
	      // create the arrayAdapter that contains the BTDevices, and set it to the ListView
	      BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
	      myListView.setAdapter(BTArrayAdapter);
      }
   }

   public void on(View view){
      if (!myBluetoothAdapter.isEnabled()) {
         Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

         Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
        		 Toast.LENGTH_LONG).show();
      }
      else{
         Toast.makeText(getApplicationContext(),"Bluetooth is already on",
        		 Toast.LENGTH_LONG).show();
      }
   }
   
   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	   // TODO Auto-generated method stub
	   if(requestCode == REQUEST_ENABLE_BT){
		   if(myBluetoothAdapter.isEnabled()) {
			   text.setText("Status: Enabled");
		   } else {   
			   text.setText("Status: Disabled");
		   }
	   }
   }
   
   public void list(View view){
	  // get paired devices
      pairedDevices = myBluetoothAdapter.getBondedDevices();
      
      // put it's one to the adapter
      for(BluetoothDevice device : pairedDevices)
    	  BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());

      Toast.makeText(getApplicationContext(),"Show Paired Devices",
    		  Toast.LENGTH_SHORT).show();
      
   }
   
   final BroadcastReceiver bReceiver = new BroadcastReceiver() {
	    public void onReceive(Context context, Intent intent) {
	        String action = intent.getAction();
	        // When discovery finds a device
	        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
	             // Get the BluetoothDevice object from the Intent
	        	 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	        	 // add the name and the MAC address of the object to the arrayAdapter
	             BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
	             BTArrayAdapter.notifyDataSetChanged();
	        }
	    }
	};
	
   public void find(View view) {
	   if (myBluetoothAdapter.isDiscovering()) {
		   // the button is pressed when it discovers, so cancel the discovery
		   myBluetoothAdapter.cancelDiscovery();
	   }
	   else {
			BTArrayAdapter.clear();
			myBluetoothAdapter.startDiscovery();
			
			registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));	
		}    
   }
   
   public void off(View view){
	  myBluetoothAdapter.disable();
	  text.setText("Status: Disconnected");
	  
      Toast.makeText(getApplicationContext(),"Bluetooth turned off",
    		  Toast.LENGTH_LONG).show();
   }
   
   @Override
   protected void onDestroy() {
	   // TODO Auto-generated method stub
	   super.onDestroy();
	   unregisterReceiver(bReceiver);
   }
		
}

4. Set the permissions

We have to declare the permissions in the AndroidManifest.xml file of our project. For this reason we add BLUETOOTH permission if we want to use any of the Bluetooth features. Also we should add BLUETOOTH_ADMIN permission, in order to discover other devices.

Open AndroidManifest.xml file and go to the respective xml tab. Then paste the following.

AndroidManifest.xml:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    
    <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.javacodegeeks.android.bluetoothtest.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>

We should mention that if we have to add BLUETOOTH_ADMIN permission, the declaration of BLUETOOTH permission is obligatory.

5. Run the application

To run the application we can’t use the Android emulator, so we have to run the app from our Android device via Eclipse.

Connect your Android device with your pc through USB. Go to Settings → Applications → Development path and enable USB debugging option.

Back to Eclipse, right click on our project → Run as → Run Configurations.

In the popup window choose the current project, go to the Target tab and choose “Always prompt to pick device” option, as you can see below. Then click Run.

BluetoothTestProjRunConf

Finally choose the running Android device and press OK.

BluetoothTestProjDeviceOn

The app will be loaded in your Android device, as you can see in the image below.

AVDBluetoothTest1

Lets press “Turn On” button in order to activate Bluetooth. A popup window will be shown as you can see below.

AVDBluetoothTest2

If we choose “No” option the status will be “Disabled” as the Bluetooth will not be activated.

AVDBluetoothTest7

Select “Yes” option and Bluetooth will be turned on.

AVDBluetoothTest3

Now click “List paired Devices”, in order to see the paired Bluetooth devices that we had been connected in the past. You can see the list in the next picture. Also notice that the status is now “Enabled” and a appropriate icon is appeared, because Bluetooth is active.

AVDBluetoothTest4_1

If we click the “Search new Devices / Cancel” button, the list of the enabled Bluetooth devices will be shown. If we press again the button, the discovery of these devices will be canceled.

AVDBluetoothTest5

Finally, press “Turn off” button. The Bluetooth is disabled and the default icon for Bluetooth is disappeared, as you can see in the next image.

AVDBluetoothTest8

Download Eclipse Project

This was an example of Bluetooth in Android. Download the Eclipse Project of this example: BluetoothTest.zip

(No Ratings Yet)
4 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

4
Leave a Reply

avatar
4 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
4 Comment authors
Negibchampaksameertogtoh Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
togtoh
Guest

how to download

sameer
Guest
sameer

It is very nice tutorial regarding Bluetooth development but can you update the code for the Android version 6.0 as it asks for location permission.

champak
Guest
champak

But how to read bluetooth data?

Negib
Guest
Negib

It’s a good example. But did you actually run this code. It should throw a NullpointerException if the device does not support Bluetooth.