How to pair Bluetooth device programmatically Android

94,360

Solution 1

How can I avoid or dismiss Android's Bluetooth pairing notification when I am doing programmatic pairing?

This seems to give you the answer, with the pin entering and all. It involves sending .setPin() whenever you get the message.

Solution 2

So, I had this question, if someone needs the answer to this working in android 4.4.2.

 IntentFilter filter = new IntentFilter(
                "android.bluetooth.device.action.PAIRING_REQUEST");


        /*
         * Registering a new BTBroadcast receiver from the Main Activity context
         * with pairing request event
         */
        registerReceiver(
                new PairingRequest(), filter);

And the code for the Receiver.

  public static class PairingRequest extends BroadcastReceiver {
        public PairingRequest() {
            super();
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
                try {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                    //the pin in case you need to accept for an specific pin
                    Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0));
                    //maybe you look for a name or address
                    Log.d("Bonded", device.getName());
                    byte[] pinBytes;
                    pinBytes = (""+pin).getBytes("UTF-8");
                    device.setPin(pinBytes);
                    //setPairing confirmation if neeeded
                    device.setPairingConfirmation(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

And in the manifest file.

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

And the broadcastReceiver.

 <receiver android:name=".MainActivity$PairingRequest">
                <intent-filter>
                    <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
                    <action android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
                </intent-filter>
</receiver>

Solution 3

How to set the pin code has been answered above (and that helped me). Yet, I share my simple code below which works with Android 6:

BluetoothAdapter mBTA = BluetoothAdapter.getDefaultAdapter();
if (mBTA.isDiscovering()) mBTA.cancelDiscovery();
mBTA.startDiscovery();
...

/** In a broadcast receiver: */

if (BluetoothDevice.ACTION_FOUND.equals(action)) { // One device found.

    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    Log.d(TAG, "Start Pairing... with: " + device.getName());
    device.createBond();
}

// If you want to auto-input the pin#:
else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){

                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    device.setPin("1234".getBytes());
}

Solution 4

Try this code:

public void pairDevice(BluetoothDevice device)
{
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    Intent intent = new Intent(ACTION_PAIRING_REQUEST);
    String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
    intent.putExtra(EXTRA_DEVICE, device);
    String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
    int PAIRING_VARIANT_PIN = 0;
    intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(EXTRA_DEVICE, device);
int PAIRING_VARIANT_PIN = 272;
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
sendBroadcast(intent);

Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(intent, REQUEST_PAIR_DEVICE);

I hope this helps

Reference: http://pastebin.com/N8dR4Aa1

Solution 5

Register a BluetoothDevice.ACTION_PAIRING_REQUEST receiver onCreate()

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
        registerReceiver(pairingReceiver, pairingRequestFilter)

on receiver set your pin using setPin() and call abortBroadcast()

val PAIRING_PIN=1234

private var pairingReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action
            if (BluetoothDevice.ACTION_PAIRING_REQUEST == action) {
                val device: BluetoothDevice? =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                val type =intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR)
                if (type == BluetoothDevice.PAIRING_VARIANT_PIN) {
                    device?.setPin(PAIRING_PIN.toByteArray())
                    abortBroadcast()
                }
            }
        }
    }

Don't forget to unregister receiver on onDestroy()

override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(pairingReceiver)
    }

if it doesn't work for you, try setting hight priority to receiver

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)          
pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1
            registerReceiver(pairingReceiver, pairingRequestFilter)

Also you can register a receiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED to read status of pairing

val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        registerReceiver(receiver, filter)
Share:
94,360
Sandip Jadhav
Author by

Sandip Jadhav

I’m working as Android Developer since 2009. Have created more than 10 Android applications which are published on Google Play and have high rates. Overall experience in IT since 2009. Strongly experienced with custom application design, location based functionality, Geographic Information System (GIS), application UI and unit testing, home-screen widgets, SQLite, Google Play publishing and support. I’m good team player, know software development processes like .net, Java. I use issue-tracking systems: BugZilla; use GIT, SVN for code versions control. Google Associate Android Developer Certification: http://bcert.me/sgietvlm Blog: http://androidmyway.in GitHub: https://github.com/sandipmjadhav Bio: http://sandipjadhav.branded.me/

Updated on January 27, 2020

Comments

  • Sandip Jadhav
    Sandip Jadhav over 4 years

    I am developing an application where I want to connect a Bluetooth device main issue is I don't want user to enter required pin instead application should do that by himself...I don't have any connection related issue...Only want to insert and complete pin authentication process by application itself.

    I found following code I am sure it is working but not sure on how to add pin in this code??

    private void pairDevice(BluetoothDevice device) {
            try {
                Log.d("pairDevice()", "Start Pairing...");
                Method m = device.getClass().getMethod("createBond", (Class[]) null);
                m.invoke(device, (Object[]) null);
                Log.d("pairDevice()", "Pairing finished.");
            } catch (Exception e) {
                Log.e("pairDevice()", e.getMessage());
            }
        }
    

    Does anyone know how to enter pin in above code or any similar code to solve problem.. Thank You

  • Denny Sharma
    Denny Sharma over 10 years
    Please help me.....I want list of device that has BT enabled and after click on particular bluetooth device, it is paired with our device
  • gregm
    gregm over 9 years
    I get the first method but what do you suggest we do with the other two blocks of code?
  • Tejas Pandya
    Tejas Pandya over 5 years
    is this solution working for android pie also ? cause im still getting confirmation dialog
  • Rodolfo Abarca
    Rodolfo Abarca over 5 years
    No, I dont think so this solution was for android 4.4.2 and android 5, not sure about android 6 and up. @TejasPandya
  • Harrish Selvarajah
    Harrish Selvarajah about 4 years
    Does this solution work without Bluetooth_Priveldge permission? Doesn't this device.setPairingConfirmation(true); line need the permisiion mentioned above to work ?
  • Rodolfo Abarca
    Rodolfo Abarca about 4 years
    @Harrish it should work, but it will depend on the device, some devices require pairing confirmation sent, and some assume that once you are connected you are paired, also this solution was for android 4.4.2 and android 5, so you should probably do something similar for android 6 and above.
  • mbo
    mbo about 4 years
    The method setPairingConfirmation needs the BLUETOOTH_PRIVILEDGED permission which is not available to third party apps. But with abortBroadcast it's working on my Pixel 4 XL!
  • mbo
    mbo about 4 years
    Best answer to this problem. It's working on my Pixel 4 XL with Android 10! If I don't call abortBroadcast the dialog pops up and closes again after 2 seconds.
  • Arthurghev
    Arthurghev almost 4 years
    @Marius could you please tell me how to do abortBroadcast.
  • mbo
    mbo almost 4 years
    @Arthurghev it's in one of the other answers stackoverflow.com/a/59925412/3979479