pair Bluetooth device - Android Bluetooth

Android examples for Bluetooth:Bluetooth Bond

Description

pair Bluetooth device

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.util.Log;

public class Main {
    public static boolean pair(String strAddr, String strPsw) {
        boolean result = false;

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();/*w  w w. j  a va 2s.  com*/
        bluetoothAdapter.cancelDiscovery();
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
        if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { 
            Log.d("mylog", "devAdd un effient!");
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            try {
                Log.d("mylog", "NOT BOND_BONDED");

                setPin(device.getClass(), device, strPsw); 

                createBond(device.getClass(), device);

                result = true;
            } catch (Exception e) {
                Log.d("mylog", "setPiN failed!");
                e.printStackTrace();
            } 
        } else {
            Log.d("mylog", "HAS BOND_BONDED");
            try {
                createBond(device.getClass(), device);
                setPin(device.getClass(), device, strPsw);
                createBond(device.getClass(), device);
                result = true;
            } catch (Exception e) {
                Log.d("mylog", "setPiN failed!");
                e.printStackTrace();
            }
        }
        return result;
    }

    static public boolean setPin(Class btClass, BluetoothDevice btDevice,
            String str) throws Exception {
        try {
            Method removeBondMethod = btClass.getDeclaredMethod("setPin",
                    new Class[] { byte[].class });
            Boolean returnValue = (Boolean) removeBondMethod.invoke(
                    btDevice, new Object[] { str.getBytes() });
            Log.e("returnValue", "" + returnValue);
        } 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