The following two tabs change content below.
Hi, I have written and developed this site to share my experience and ideas with other colleagues. I also started to prepare interview questions and answers for job seekers. I hope it will help you a lot.

What is Bluetooth?
Bluetooth is a wireless technology standard for exchanging data over short distances from fixed and mobile devices and building personal area networks (PANs). Invented by telecom vendor Ericsson in 1994, it was originally conceived as a wireless alternative to RS-232 data cables.

How Bluetooth works in android?
The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features.

Using Bluetooth we can perform the following operations:
• Scan for other Bluetooth devices
• Query the local Bluetooth adapter for paired Bluetooth devices
• Establish RFCOMM channels
• Connect to other devices through service discovery
• Transfer data to and from other devices
• Manage multiple connections

Android Bluetooth API:
All of the Bluetooth APIs is available in the android.bluetooth package.
We are going to discuss some important classes and interfaces you will need to create Bluetooth connections:

Classes and Interfaces Description
Bluetooth Adapter (BluetoothAdapter class) The BluetoothAdapter lets you perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for connection requests from other devices, and start a scan for Bluetooth LE devices.
Bluetooth Device (BluetoothDevice class) A BluetoothDevice lets you create a connection with the respective device or query information about it, such as the name, address, class, and bonding state.
Bluetooth socket (BluetoothSocket class and BluetoothServerSocket class) The interface for Bluetooth Sockets is similar to that of TCP sockets: Socket and ServerSocket. On the server side, use a BluetoothServerSocket to create a listening server socket. When a connection is accepted by the BluetoothServerSocket, it will return a new BluetoothSocket to manage the connection. On the client side, use a single BluetoothSocket to both initiate an outgoing connection and to manage the connection.
BluetoothA2dp class implements BluetoothProfile interface Defines how high quality audio can be streamed from one device to another over a Bluetooth connection. “A2DP” stands for Advanced Audio Distribution Profile.
BluetoothHealth class implements BluetoothProfile interface Represents a Health Device Profile proxy that controls the Bluetooth service.
BluetoothHealthCallback class An abstract class that you use to implement BluetoothHealth callbacks. You must extend this class and implement the callback methods to receive updates about changes in the application’s registration state and Bluetooth channel state.
BluetoothHealthAppConfiguration class Represents an application configuration that the Bluetooth Health third-party application registers to communicate with a remote Bluetooth health device.
BluetoothProfile.ServiceListener interface An interface that notifies BluetoothProfile IPC clients when they have been connected to or disconnected from the service (that is, the internal service that runs a particular profile)

 

Required Bluetooth Permissions for android application:

In order to use Bluetooth features in your application, you must declare the Bluetooth permission BLUETOOTH. You need this permission to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data.

If you want your app to initiate device discovery or manipulate Bluetooth settings, you must also declare the BLUETOOTH_ADMIN permission.
Note: If you use BLUETOOTH_ADMIN permission, then you must also have the BLUETOOTH permission.

You can declare the permission in AndroidManifest.xml file like below:

<manifest … >
<uses-permission android:name=”android.permission.BLUETOOTH” />

</manifest>

 

So now let’s start with an example to discover new and already paired devices list.

1. Create a project with name “Bluetooth” using android studio.

bluetooth_pro

2. Now create the MainActivity.java file under package “com.kpblog.bluetooth” and paste below code into this.

package com.kpblog.bluetooth;

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

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import android.app.Activity;
import android.app.ProgressDialog;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

public class MainActivity extends Activity {
   private TextView mStatusTv;
   private Button mActivateBtn;
   private Button mPairedBtn;
   private Button mScanBtn;
   
   private ProgressDialog mProgressDlg;
   
   private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
   
   private BluetoothAdapter mBluetoothAdapter;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      setContentView(R.layout.activity_main);
      
      mStatusTv        = (TextView) findViewById(R.id.tv_status);
      mActivateBtn      = (Button) findViewById(R.id.btn_enable);
      mPairedBtn           = (Button) findViewById(R.id.btn_view_paired);
      mScanBtn         = (Button) findViewById(R.id.btn_scan);
      
      mBluetoothAdapter  = BluetoothAdapter.getDefaultAdapter();
      
      mProgressDlg      = new ProgressDialog(this);
      
      mProgressDlg.setMessage("Scanning...");
      mProgressDlg.setCancelable(false);
      mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
              
              mBluetoothAdapter.cancelDiscovery();
          }
      });
      
      if (mBluetoothAdapter == null) {
         showUnsupported();
      } else {
         mPairedBtn.setOnClickListener(new View.OnClickListener() {          
            @Override
            public void onClick(View v) {
               Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
               
               if (pairedDevices == null || pairedDevices.size() == 0) { 
                  showToast("No Paired Devices Found");
               } else {
                  ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
                  
                  list.addAll(pairedDevices);
                  
                  Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
                  
                  intent.putParcelableArrayListExtra("device.list", list);
                  
                  startActivity(intent);                
               }
            }
         });
         
         mScanBtn.setOnClickListener(new View.OnClickListener() {            
            @Override
            public void onClick(View arg0) {
               mBluetoothAdapter.startDiscovery();
            }
         });
         
         mActivateBtn.setOnClickListener(new View.OnClickListener() {            
            @Override
            public void onClick(View v) {
               if (mBluetoothAdapter.isEnabled()) {
                  mBluetoothAdapter.disable();
                  
                  showDisabled();
               } else {
                  Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                  
                   startActivityForResult(intent, 1000);
               }
            }
         });
         
         if (mBluetoothAdapter.isEnabled()) {
            showEnabled();
         } else {
            showDisabled();
         }
      }
      
      IntentFilter filter = new IntentFilter();
      
      filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
      filter.addAction(BluetoothDevice.ACTION_FOUND);
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
      filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
      
      registerReceiver(mReceiver, filter);
   }
   
   @Override
   public void onPause() {
      if (mBluetoothAdapter != null) {
         if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
         }
      }
      
      super.onPause();
   }
   
   @Override
   public void onDestroy() {
      unregisterReceiver(mReceiver);
      super.onDestroy();
   }
   
   private void showEnabled() {
      mStatusTv.setText("Bluetooth is On");
      mStatusTv.setTextColor(Color.BLUE);
      
      mActivateBtn.setText("Disable");      
      mActivateBtn.setEnabled(true);
      
      mPairedBtn.setEnabled(true);
      mScanBtn.setEnabled(true);
   }
   
   private void showDisabled() {
      mStatusTv.setText("Bluetooth is Off");
      mStatusTv.setTextColor(Color.RED);
      
      mActivateBtn.setText("Enable");
      mActivateBtn.setEnabled(true);
      
      mPairedBtn.setEnabled(false);
      mScanBtn.setEnabled(false);
   }
   
   private void showUnsupported() {
      mStatusTv.setText("Bluetooth is unsupported by this device");
      
      mActivateBtn.setText("Enable");
      mActivateBtn.setEnabled(false);
      
      mPairedBtn.setEnabled(false);
      mScanBtn.setEnabled(false);
   }
   
   private void showToast(String message) {
      Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
   }
   
   private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
       public void onReceive(Context context, Intent intent) {           
           String action = intent.getAction();
           
           if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
              final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
               
              if (state == BluetoothAdapter.STATE_ON) {
                 showToast("Enabled");
                  
                 showEnabled();
               }
           } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
              mDeviceList = new ArrayList<BluetoothDevice>();
            
            mProgressDlg.show();
           } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
              mProgressDlg.dismiss();
              
              Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
              
              newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
            
            startActivity(newIntent);
           } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
              BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
              
              mDeviceList.add(device);
              
              showToast("Found device " + device.getName());
           }
       }
   };
}//End of activity 



Explanation for this activity
In this activity we have initialised bluetooth adapter like:

mBluetoothAdapter   = BluetoothAdapter.getDefaultAdapter();

Written the BroadcastReceiver where we will get the notification if after device discover started like:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {           
        String action = intent.getAction();
        
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
           final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            
           if (state == BluetoothAdapter.STATE_ON) {
              showToast("Enabled");
               
              showEnabled();
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
           mDeviceList = new ArrayList<BluetoothDevice>();
         
         mProgressDlg.show();
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           mProgressDlg.dismiss();
           
           Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
           
           newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
         
         startActivity(newIntent);
        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
           
           mDeviceList.add(device);
           
           showToast("Device Founded" + device.getName());
        }
    }
};

In this activity also mention the action to start device discover etc like:
To discover already paired and new device:

mBluetoothAdapter.startDiscovery();

get paired devices list:

mBluetoothAdapter.getBondedDevices();


3. Once you done with MainActivity.java now create anther Activity with named DeviceListActivity.java under same package. And paste below code into this activity.

package com.kpblog.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * @author Khushvinders
 */

public class DeviceListActivity extends Activity {

    private ListView mListView;
    private DeviceListAdapter mAdapter;
    private ArrayList<BluetoothDevice> mDeviceList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.device_list_layout);

        mDeviceList       = getIntent().getExtras().getParcelableArrayList("device.list");
        mListView     = (ListView) findViewById(R.id.lv_paired);
        mAdapter      = new DeviceListAdapter(this);

        mAdapter.setData(mDeviceList);
        mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
            @Override
            public void onPairButtonClick(int position) {
                BluetoothDevice device = mDeviceList.get(position);

                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    unpairDevice(device);
                } else {
                    showToast("Pairing...");
                    pairDevice(device);
                }
            }
        });

        mListView.setAdapter(mAdapter);
        registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mPairReceiver);
        super.onDestroy();
    }

    private void showToast(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }

    private void pairDevice(BluetoothDevice device) {
        try {
            Method method = device.getClass().getMethod("createBond", (Class[]) null);
            method.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unpairDevice(BluetoothDevice device) {
        try {
            Method method = device.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(device, (Object[]) null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                final int state       = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

                if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
                    showToast("Paired");
                } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
                    showToast("Unpaired");
                }

                mAdapter.notifyDataSetChanged();
            }
        }
    };
}//End of activity 

In this activity written the code for pair or un-pair device
//Pair Device and in below code device is object of BluetoothDevice

Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);

//Un-Pair Device

Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);

4. So now creating the adapter to show the list of paired or new device list. Create a class with named DeviceListAdapter.java under same package. And copy below code into this class.

package com.kpblog.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;

/**
 * @author Khushvinders
 */

public class DeviceListAdapter extends BaseAdapter {
   private LayoutInflater mInflater;
   private List<BluetoothDevice> mData;
   private OnPairButtonClickListener mListener;
   
   public DeviceListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }
   
   public void setData(List<BluetoothDevice> data) {
      mData = data;
   }
   
   public void setListener(OnPairButtonClickListener listener) {
      mListener = listener;
   }
   
   public int getCount() {
      return (mData == null) ? 0 : mData.size();
   }

   public Object getItem(int position) {
      return null;
   }

   public long getItemId(int position) {
      return position;
   }

   public View getView(final int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      
      if (convertView == null) {       
         convertView          =  mInflater.inflate(R.layout.device_detail_layout, null);
         
         holder              = new ViewHolder();
         
         holder.nameTv     = (TextView) convertView.findViewById(R.id.tv_name);
         holder.addressTv   = (TextView) convertView.findViewById(R.id.tv_address);
         holder.pairBtn    = (Button) convertView.findViewById(R.id.btn_pair);
         
         convertView.setTag(holder);
      } else {
         holder = (ViewHolder) convertView.getTag();
      }
      
      BluetoothDevice device = mData.get(position);

      holder.nameTv.setText(device.getName());
      holder.addressTv.setText(device.getAddress());
      holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
      holder.pairBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (mListener != null) {
               mListener.onPairButtonClick(position);
            }
         }
      });
  return convertView;
   }

   static class ViewHolder {
      TextView nameTv;
      TextView addressTv;
      TextView pairBtn;
   }
   
   public interface OnPairButtonClickListener {
      public abstract void onPairButtonClick(int position);
   }
}

5. Now for user prospective we need to create layouts one by one. Create a layout with name “activity_main.xml” under res/layout folder and copy below code into this.

<LinearLayout 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:orientation="vertical"
    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:textColor="#ff0000"
       />

    <Button
        android:id="@+id/btn_enable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"        
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:text="Enable"
        />
    
    <Button
        android:id="@+id/btn_view_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"        
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:enabled="false"
        android:text="Paired Devices"
         />
    
    <Button
        android:id="@+id/btn_scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"        
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:enabled="false"
        android:text="Scan Devices"
         />
</LinearLayout>

6. Create layout “device_list_layout.xml” for DeviceListActivity.java and use below code for this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:text="List of Devices" />
    
    <ListView
        android:id="@+id/lv_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000" />

</LinearLayout>

 

7. Create layout “device_detail_layout.xml” for DeviceListAdapter.java and use below code for this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <Button
        android:id="@+id/btn_pair"
        android:layout_width="125dp"
        android:layout_height="wrap_content"        
        android:layout_centerInParent="true"
        android:layout_alignParentRight="true"
        android:text="Pair" />
    
    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btn_pair"
        android:layout_alignTop="@+id/btn_pair"
        android:layout_alignParentLeft="true"
        android:textSize="16sp"
        android:textColor="#000000"
        android:text="Galaxy Nexus" />
   
    <TextView
        android:id="@+id/tv_address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btn_pair"
        android:layout_alignParentLeft="true"
        android:layout_alignBottom="@+id/btn_pair"
        android:text="000000000" />
    
</RelativeLayout>

8. AndroidManifest.xml use below code:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".DeviceListActivity"
            android:label="@string/title_activity_device_list"
            android:theme="@style/AppTheme.NoActionBar"></activity>
    </application>

</manifest>

 

bluetooth1 bluetooth2 bluetooth3

 

419 total views, 2 views today

One thought on “Describe about Bluetooth and example to discover new and paired device list”

Leave a Reply

Your email address will not be published. Required fields are marked *