Bluetooth in Android-Part I

This time I thought of posting some basic information about Bluetooth in Android.

Android supports Bluetooth APIs to access Bluetooth functionalities.

Four major tasks necessary to communicate using Bluetooth are:

1) Setting up Bluetooth

2) Finding devices

3) Connecting devices

4) Transferring data between devices

In this post I’m going to discuss about how to check whether the device supports Bluetooth and if it does, how to enable the same.

Here we go!! 🙂

First of all we need to check whether the device supports Bluetooth. For every Bluetooth activity we need a class named BluetoothAdapter which controls the local Bluetooth device. So the first step is getting the Bluetooth adapter of the device which is done using the method getDefaultAdapter().

Just check the code below:

BluetoothAdapter myBTadapter=BluetoothAdapter.getDefaultAdapter();

Now, as you know now that the getDefaultAdapter() method returns the local Bluetooth adapter, if it returns null then we can easily understand that the device doesn’t support Bluetooth. So let’s display a toast saying it doesn’t support Bluetooth.

Here is the code.

BluetoothAdapter myBTadapter=BluetoothAdapter.getDefaultAdapter();
if(myBTadapter==null)
{
 Toast.makeText(getApplicationContext(), "Device doesn't support Bluetooth", Toast.LENGTH_LONG).show();
 }

Now, if  getDefaultAdapter method doesn’t return null and if Bluetooth is disabled we need to enable the same.

Let’s see how it is done. First of all look at the code below.

if(!myBTadapter.isEnabled())
 {
 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
 startActivityForResult(enableBtIntent, REQ_BT_ENABLE);
 Toast.makeText(getApplicationContext(), "Enabling Bluetooth!!", Toast.LENGTH_LONG).show();
 }

First of all what we need to do is check whether Bluetooth is enabled on the device using method isEnabled(). It returns a Boolean value. If the value returned is false, the Bluetooth is not enabled. So we need to enable it. For that we need to create an intent with action  ACTION_REQUEST_ENABLE (which is a BluetoothAdapter static constant).

The intent is passed to startActivityForResult(). The second argument of the method is REQ_BT_ENABLE which is an integer constant which is passed back to onActivityResult() as the requestCode.

The code below shows the onActivityResult():

@Override 
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQ_BT_ENABLE){
if (resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(), "BlueTooth is now Enabled", Toast.LENGTH_LONG).show();
}
 if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Error occured while enabling.Leaving the application..", Toast.LENGTH_LONG).show();
 ///finish();
 }
 }
 }//onActivityResult

We can disable the Bluetooth using disable() method as shown below:

myBTadapter.disable();

The Whole Code :

package com.deepthi.mybluetoothenabledemo;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
public class MyBluetoothEnabledemoActivity extends Activity {
 /** Called when the activity is first created. */
 BluetoothAdapter myBTadapter;
 Integer REQ_BT_ENABLE=1;
 CheckBox enable;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 myBTadapter=BluetoothAdapter.getDefaultAdapter();
 enable=(CheckBox)findViewById(R.id.cboxEnable);
 enable.setOnCheckedChangeListener(new OnCheckedChangeListener() {

 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 // TODO Auto-generated method stub
 if(buttonView.isChecked())
 {
 if(myBTadapter==null)
 {
 Toast.makeText(getApplicationContext(), "Device doesn't support Bluetooth", Toast.LENGTH_LONG).show();
 }
 else
 {
 if(!myBTadapter.isEnabled())
 {
 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
 startActivityForResult(enableBtIntent, REQ_BT_ENABLE);
 Toast.makeText(getApplicationContext(), "Enabling Bluetooth!!", Toast.LENGTH_LONG).show();
 }
 }
 }
 else
 {
 Toast.makeText(getApplicationContext(), "Disabling Bluetooth!!", Toast.LENGTH_LONG).show();
 myBTadapter.disable();
 }
 }
 });

 }
 @Override 
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQ_BT_ENABLE){
if (resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(), "BlueTooth is now Enabled", Toast.LENGTH_LONG).show();
}
 if(resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Error occured while enabling.Leaving the application..", Toast.LENGTH_LONG).show();
 ///finish();
 }
 }
 }//onActivityREsult
}

In the Manifest:

<uses-permission android:name="android.permission.BLUETOOTH" />
 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

The XML code:

<?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="fill_parent"
 android:orientation="vertical" >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello" />
<CheckBox
 android:id="@+id/cboxEnable"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Enable" />
</LinearLayout>

Try this on a real Android device. As the emulator does not support Bluetooth. Check this link.

Hope this post has been useful to you. 🙂

, , , , , , , , ,

  1. #1 by venky on May 17, 2012 - 5:43 pm

    thank u for posting new tutorial

    thank u vry much

    • #2 by Deepthi G on May 17, 2012 - 6:47 pm

      hey Venky,
      You are welcome..:)Keep Reading.. 🙂

  2. #3 by rams on May 22, 2012 - 4:28 pm

    Hi Deepthi,
    Nice Tutorials .
    i’m also giving some tutorials on Android you can visit http://ramscreative.blogspot.in/

    • #4 by Deepthi G on May 24, 2012 - 5:13 pm

      Hey Rams,

      Thanks a lot buddy.. 🙂 .I’ll surely visit your blog..Keep Reading… 🙂

  3. #5 by RK on May 23, 2012 - 3:10 pm

    it is very useful for me.. Thank you….

    • #6 by Deepthi G on May 24, 2012 - 5:10 pm

      hey RK,
      Glad that this post was useful to you.. Keep Reading..:)

  4. #7 by Kumar on August 24, 2012 - 11:51 am

    How can i scan bluetooth devices???????
    How can i connect to scan bluetooth devices???

    • #8 by Deepthi G on August 29, 2012 - 5:55 pm

      Hey Kumar,
      Try this and also check ma post Bluetooth in android part-II

      mBluetoothAdapter.startDiscovery();
      mReceiver = new BroadcastReceiver() {
      public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (BluetoothDevice.ACTION_FOUND.equals(action))
      {
      // Get the BluetoothDevice object from the Intent
      BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      // Add the name and address to an array adapter to show in a ListView
      mArrayAdapter.add(device.getName() + “\n” + device.getAddress());
      }
      }
      };
      IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
      registerReceiver(mReceiver, filter);

  5. #9 by Haris on August 28, 2012 - 10:42 am

    Really nice tutorial and it is very useful to me……..

    • #10 by Deepthi G on August 29, 2012 - 5:42 pm

      Hey Haris
      Thanks a lot 🙂 Glad that this was useful to you..:)

  6. #11 by Haris on August 31, 2012 - 12:02 pm

    Have you tried the blue-tooth chat example along with the android samples.
    For the last three days I am playing with this sample code…

    I successfully installed on my device and it’s working…….

    The problem is that after scanning it shows the list of available devices but when I try to pair with the device it shows “unable to connect” ….

    On the other device I set the device discoverable option on…..
    Any Idea………

  7. #12 by saket on September 5, 2012 - 2:17 pm

    nice tutorials
    can you help me for how to read pdf file from SD card?

  8. #13 by Raj on November 5, 2012 - 6:17 pm

    hi Deepi,

    Thank you very much ,its nice tutorials,i am very proud to be visit this site,i am just beginner for android platform.i am going to do a project using Bluetooth to control the robot or some more devices.i don’t know how to write a program for Bluetooth controllable device using android and i need to learn how to make a layout using eclipse ..i need step by step procedure for easy understanding.please help me as soon as possible,i hope you can do this …..

    i am waiting for your response …

    Thank you

  9. #14 by John on November 27, 2012 - 5:11 am

    Hi,
    Your tutorial is usefull, but I have a problem with connecting a device and send message. Can you help me? Your tutorials are easier then other.
    Thanks you. John

  10. #15 by Rashi.. Coorg.. on November 27, 2012 - 3:15 pm

    Thank u.. very nice on.. 🙂

  11. #16 by dinshanh on December 13, 2012 - 11:34 am

    Have you tried to implement profiles in bluetooth ? Like OBEX , SPP ? If so kindly let me know !

  12. #17 by Danel on December 18, 2012 - 6:49 pm

    Ahh thank you! Been struggling with BT few days now. Thanks to your tutorial i succeeded. Also, thanks for the Toast example. Am trying to create a BT Native Extension for Adobe AIR, and trying to learn Android SDK isnt as simple as i thought!
    Other than that, merry christmas! 🙂

  13. #18 by bborncr on December 28, 2012 - 10:24 pm

    Thanks for the tutorial, it really helped me out. The snowflakes scared me at first…I thought I was hallucinating from too much coffee!

  14. #19 by Krunal Panchal on February 13, 2013 - 2:23 pm

    Hey Deepthi…nice tutorial….give me ur email id…I want to discuss my android project with u…thanks..

  15. #20 by Srikanth Bhandary on March 18, 2013 - 10:28 am

    Deepthi thank you for your tutorial.. Can you please explain how to send images via blue tooth. As I worked in VBA and newer to android, now I am developing app for retail shop for paperless bill printing. I have done with all the coding part and left with the Bluetooth transfer. Your help will be appreciated.

  16. #21 by shan on March 18, 2013 - 3:50 pm

    how can i use emulator in bluetooth application , ????

  17. #22 by shan on March 18, 2013 - 5:49 pm

    how to pairing the devices

  18. #23 by mamandar on December 12, 2013 - 8:52 am

    Thanks for sharing…nice tutorial

  19. #24 by !bug on December 16, 2013 - 7:35 am

    Excelente

  20. #25 by shubham patni on May 1, 2014 - 1:01 pm

    thanks dear 🙂

  21. #26 by chandru on May 11, 2015 - 11:17 pm

    Hi Deepthi, this is chandru. i had doing bluetooth communication apps. programmatically connect two device. but unfortunately activity is closed. but device is connected. sudenly closed activity.

    Note: How to connect two device programmatically and after connecting two device programmatically taking picture every 5 seconds. i did this process. But some times unfortunately activity is closed.

  1. Bluetooth in Android-Part II « Android Desk

Leave a reply to Srikanth Bhandary Cancel reply