• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • About
  • Projects
    • GStaticMap WP Plugin
  • Contact
  • Privacy Policy

Lorenz Blog

All About Web & Mobile Application Development

  • Featured Articles
  • Gadgets
    • Android
    • Blackberry
  • Programming
    • Android
    • PHP
    • Java Script
    • MySQL
    • Postgresql
    • Flex
    • Web
  • Software
    • Mac OS
    • Windows
    • Linux
  • Web
You are Here » Home >> Information Technology >> Programming >> Android >> How to Programmatically Pair or Unpair Android Bluetooth Device

How to Programmatically Pair or Unpair Android Bluetooth Device

February 20, 2014 by Lorensius Londa 24 Comments

In bluetooth wireless communication, if two devices want to connect and share data, they have to be paired first. To be paired means the two devices are aware of each other’s existence and trusted each other. 

Using Android Bluetooth API, we can use createBond method to pair with a device or removeBond to unpair. This  is an asynchronous call so that it will return immediately. To catch the pairing process, we have to register a BroadcastReceiver with ACTION_BOND_STATE_CHANGED intent to catch the process.

android bluetooth pair  android bluetooth device list
(apk and source code at the bottom if this post)

How to pair

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

How to Unpair

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

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

The receiver to catch the pairing process:

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");
	        	 }

	        }
	    }
	};

Register receiver

IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairReceiver, intent);

For each changed state, the intent will carry extra fields EXTRA_BOND_STATE and EXTRA_PREVIOUS_BOND_STATE. Using the value from the  extra fields we can determine the state of pairing process.

State paired if current state is BOND_BONDED and previous state is BOND_BONDING.
State unpaired if current state is BOND_NONE and previous state is BOND_BONDED.

Download the sample APK and source code from github

[ad#ad-720×90]

Facebooktwitterredditpinterestlinkedinmailby feather

Related posts:

  1. How to Programmatically Scan or Discover Android Bluetooth Devices
  2. How to Create Android Image Picker
  3. How to Select and Crop Image on Android
  4. Simple JSON RPC Client for Android

Filed Under: Android Tagged With: Android, bluetooth, pairing, programmatically

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

  1. Ivan says

    February 21, 2014 at 2:35 am

    I have problem with some devices that they are listed as bonded (paired) but when I try to connect (open bluetooth socket) pairing dialog popup anyway.. Did u experienced similar behaviour? Mostly affected devices are with newer versions of android (let”s say 4.1 and later..).. Thanks

    Reply
    • Lorensius Londa says

      February 21, 2014 at 7:17 am

      Hi Ivan, i never encountered that issue. Have you tried to check the bond state before making the connection (device.getBondState())? Is the state BONDED_NONE though it is listed on paired devices?

      Reply
      • Ivan says

        February 22, 2014 at 4:13 am

        That is the funny thing.. When I check state is bonded but when I try to open bluetooth socket pairing dialog come… :S

        Reply
        • Lorensius Londa says

          February 22, 2014 at 11:37 am

          Hmm, that’s weird..hehe

          Reply
  2. Jorge Cunha says

    May 10, 2014 at 4:49 am

    Hi, when I click in “pair” button appears an pop-up to put the PIN, it´s possible to put the pin in the code? in one variable?

    Reply
  3. Jules says

    May 15, 2014 at 3:46 pm

    Well it doesn’t work here either, tried in tablets with 4.0 and 4.1.

    Reply
  4. Miguel says

    June 27, 2014 at 4:24 pm

    I created a button that is on the side of pair button .. and I want that button to connect to the corresponding device.

    How ? Please.

    Thanks.

    Reply
  5. Tle says

    September 23, 2014 at 4:34 pm

    Hi,

    I tried to follow your code to pair with selected bluetooth device in listview. But it is not working.
    I don’t know how to call pairDevice() in :

    Listview.setOnItemClickListener( new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView parent, View view,
    int position, long id)
    {
    // TODO Auto-generated method stub
    //I want to pair device over here
    }
    });

    Plz help, Thanks

    Reply
    • Kiran Ahuja says

      December 24, 2017 at 4:13 pm

      Hey, evTen i have d same problem.. could u get any solution for it?

      Reply
  6. Ammy says

    September 26, 2014 at 2:22 pm

    I did not get any Activity Screen of button like pair/unpair device etc.
    I only got a blank activity and my bluetooth is automatically on when app is opening

    Reply
    • Ammy says

      September 26, 2014 at 2:53 pm

      sorry I was wrong… Please delete this comment.

      Reply
  7. Matthias Hartmann says

    October 25, 2014 at 6:35 pm

    Hi Lorensius,

    I want to pair a device that only supports 4 digit PINs ( an ion Icade see: http://forum.xda-developers.com/showthread.php?t=2267109 ).
    Is it possible, to force android to use a 4 digit PIN instead of the random generated 6 digit PIN?
    If yes, do you know how your code has to be modified to accomplish this?
    Thanks!

    Best
    Matthias

    Reply
  8. Adi says

    November 5, 2014 at 9:07 pm

    Hi Lorensius, i would to thank you for this great tutorial. But can you help me expanding this project where it can connect the mobile phone with the listed pair device and send serial data? If you can i would be very grateful to you. I need to complete this for my Final Year Project.

    Reply
  9. Danny H says

    November 8, 2014 at 4:27 am

    Hi Lorensius,

    Excellent example you have here! Unfortunately, I seem to be running into some troubles when pairing with an Arduino Bluetooth module. Your software seems to pair properly with the module form the Android side of things, but the module does not seem to acknowledge this. I was wondering if you could give some tips on how to send and receive data via Bluetooth rather than just pair devices.

    Thanks!

    Reply
  10. Dani says

    November 30, 2014 at 5:49 pm

    Hi, first, a great contribution. I have a question, you can connect to a device with a default PIN (eg 1234) and that the user does not see the next window “Bluetooth pairing request”?

    Thanks!

    Reply
  11. Eamon says

    December 11, 2014 at 11:56 pm

    Excellent, this is exactly what I’ve been looking for, thanks.

    Reply
  12. Shiv says

    December 21, 2014 at 8:55 pm

    Hey Bro i want this code plz send me this code on the mail is.

    Reply
  13. Izach says

    January 24, 2015 at 10:29 pm

    Thanks to this sir Lorenz 😉

    Thumbs up!

    Reply
  14. harsh mehta says

    February 24, 2015 at 8:38 pm

    i want send a enable bluetooth request to all nearby available devices. the reason being is .. i am working on a project called bluetooth proximity marketing and i can’t trigger devices unless these devices have enabled their bluetooth .. so, any code which can be incorporated with this bluetooth Proximity marketing device. which can send the request to enable their bluetooth remotely .. is it possible ?

    Reply
  15. Alexander says

    March 4, 2015 at 10:56 pm

    Hi, Lorensius .

    I need to connect two devices w/o PIN or any other thing, which requires user’s attantion. One program tryes to connect to same program on other device. I’ve implemented this methods of programmatically pairing, so my programm now not ask the PIN, but still ask the confirmation for pairing.. How i can solve this? Does way to connect w/o PIN exists?

    Thanks.
    Alexander.

    Reply
  16. issam says

    April 15, 2015 at 9:08 am

    could you help me connecting device via bluetooth without user confirmation
    help me please i’m realy in a bad situation of not finding it out for my licence project

    Reply
  17. Mitch says

    October 27, 2016 at 10:23 am

    Thanks for the tutorial. It was very helpful.

    –Mitch
    http://codingwithmitch.com/
    https://www.youtube.com/channel/UCoNZZLhPuuRteu02rh7bzsw

    Reply
  18. Hameed Ibrahim says

    April 6, 2017 at 6:02 pm

    Hi
    how to automatically pair the bluetooth device without popup dialog

    Reply
  19. Hameed Ibrahim says

    April 7, 2017 at 8:22 pm

    Hi
    How to do android pairing bluetooth devices without dialog with pin

    Reply

Leave a Reply Cancel reply

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

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

  • Facebook
  • GitHub
  • Google+
  • Instagram
  • Twitter
  • YouTube

Featured Articles

How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Blue Bamboo P25 Printer Android Demo Application With Source Code

Simple JSON RPC Client for Android

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

Footer

Recent Comments

  • Aditya Dabas on About
  • Ayten Göksenin Barutçu on How to Make Android Map Scrollable Inside a ScrollView Layout
  • mang jojot on About
  • Hussain on How to Programmatically Scan or Discover Android Bluetooth Devices

Recent Posts

  • How to Fix Blank Screen on WordPress Add/Edit Post Page
  • How to Programmatically Restart the ESP32 Board
  • How to Get Hardware Info of ESP32
  • How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Latest Tweets

To protect our users from spam and other malicious activity, this account is temporarily locked. Please log in to https://twitter.com to unlock your account.

Copyright © 2023 · Magazine Pro on Genesis Framework · WordPress · Log in