auto Bond Bluetooth device - Android Bluetooth

Android examples for Bluetooth:Bluetooth Bond

Description

auto Bond Bluetooth device

Demo Code

import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;
import android.util.Log;

public class Main {

  static public boolean autoBond(Class<?> devicesClass, BluetoothDevice device, String pin) {
    try {/*from  w  w w  .  j av  a 2 s. c  om*/
      if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
        boolean bonded = createBond(device.getClass(), device); // ?????????
        boolean pined = setPin(device.getClass(), device, pin);
        return bonded && pined;
      } else {
        Log.i("Bluetooth", device.getName() + "???????????");
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }

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

  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;

  }
}

Related Tutorials