auto Bond Bluetooth Device - Android android.bluetooth

Android examples for android.bluetooth:Bluetooth Pair

Description

auto Bond Bluetooth Device

Demo Code

import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;

public class Main {

  static public boolean autoBond(Class<?> devicesClass, BluetoothDevice device, String pin) {
    try {// ww w . jav  a2 s  .  c o  m
      if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
        boolean bonded = createBond(device.getClass(), device);
        boolean pined = setPin(device.getClass(), device, pin);
        return bonded && pined;
      } else {
        return true;

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

    return false;
  }

  static public boolean setPin(Class<?> btClass, BluetoothDevice btDevice, String str) throws Exception {
    try {
      boolean result = false;
      int count = 0;
      Method removeBondMethod = btClass.getDeclaredMethod("setPin", new Class[] { byte[].class });
      while (!result && count < 3) {
        result = (Boolean) removeBondMethod.invoke(btDevice, str.getBytes());
        count++;
      }
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return true;
  }

  static public boolean createBond(Class<?> btClass, BluetoothDevice btDevice) throws Exception {
    Method createBondMethod = btClass.getMethod("createBond");
    Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
    return returnValue.booleanValue();
  }
}

Related Tutorials