如何在没有用户交互的情况下以编程方式配对蓝牙设备

时间:2015-03-03 10:29:41

标签: android bluetooth

我知道有很多这样的问题,但是没有一个能解决我的问题。我正在尝试在两个设备之间以编程方式实现蓝牙配对。我能够配对设备,但问题是它需要用户按下我不想在我的应用程序中的配对按钮。我希望它们在没有任何用户交互的情况下连接,或者如果不可能,它应该只要求一个设备按下配对按钮并且应该配对。我有一台三星电视的工作方式,当我尝试连接我的Android手机的蓝牙与它..我的手机上弹出一对引脚请求,当我点击它配对它没有在电视上显示任何东西他们俩都配对了。我需要在我的应用中实现这一点。我已经尝试过这段代码,但它没有取密码并连接它仍然要求输入密码。

public void setBluetoothPairingPin(BluetoothDevice device)
{
    byte[] pinBytes = convertPinToBytes("0000");
    try {
          Log.d(TAG, "Try to set the PIN");
          Method m = device.getClass().getMethod("setPin", byte[].class);
          m.invoke(device, pinBytes);
          Log.d(TAG, "Success to add the PIN.");
          try {
                device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
                Log.d(TAG, "Success to setPairingConfirmation.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e(TAG, e.getMessage());
                e.printStackTrace();
            } 
        } catch (Exception e) {
          Log.e(TAG, e.getMessage());
          e.printStackTrace();
        }
}

我一直在寻找解决方案近一个星期。我们非常感谢能够实现上述目标的任何想法/建议。

2 个答案:

答案 0 :(得分:5)

你应该试试这个......!

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

mAdapter.setData(mDeviceList);
        mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {            
            @Override
            public void onPairButtonClick(int position) {               
                BluetoothDevice device = mDeviceList.get(position);

                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    unpairDevice(device);
                } else {
                    showToast("Pairing...");
                    pairDevice(device);//here is calling
                }
            }
        });

答案 1 :(得分:0)

`You should try this code on while pair button clicked,

String strPsw = "FBK645NKL"
mAdapter.setData(mDeviceList);
mAdapter.setListener(new OnPairButtonClickListener() {

            @Override
            public void onPairButtonClick(int position) {
                BluetoothDevice device = mDeviceList.get(position);

                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    unpairDevice(device);
                }  else {
                    Log.d("mylog", "HAS BOND_BONDED");
                    try {
                        ClsUtils.createBond(device.getClass(), device);
                        ClsUtils.setPin(device.getClass(), device, strPsw); //
                        ClsUtils.createBond(device.getClass(), device);
//                      remoteDevice = device; // ?remoteDevice
                        result = true;
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Log.d("mylog", "setPiN failed!");
                        e.printStackTrace();
                    }
                }
                return;
            }

        });

and You must write a code for ClsUtils.java 

//ClsUtils code for Bluetooth Device Pairing and Bonding...

import java.lang.reflect.Field;
import java.lang.reflect.Method;

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

public class ClsUtils {

    /**
     * ?platform/packages/apps/Settings.git
     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    static public boolean createBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method createBondMethod = btClass.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }

    /**
     * ?platform/packages/apps/Settings.git
     * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
     */
    @SuppressWarnings("unchecked")
    static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method removeBondMethod = btClass.getMethod("removeBond");
        Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    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) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;

    }

    //
    @SuppressWarnings("unchecked")
    static public boolean cancelPairingUserInput(Class btClass,
            BluetoothDevice device)

    throws Exception {
        Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
        // cancelBondProcess()
        Boolean returnValue = (Boolean) createBondMethod.invoke(device);
        return returnValue.booleanValue();
    }

    //
    @SuppressWarnings("unchecked")
    static public boolean cancelBondProcess(Class btClass,
            BluetoothDevice device)

    throws Exception {
        Method createBondMethod = btClass.getMethod("cancelBondProcess");
        Boolean returnValue = (Boolean) createBondMethod.invoke(device);
        return returnValue.booleanValue();
    }

    /**
     *
     * @param clsShow
     */
    static public void printAllInform(Class clsShow) {
        try {
            //
            Method[] hideMethod = clsShow.getMethods();
            int i = 0;
            for (; i < hideMethod.length; i++) {
                Log.e("method name", hideMethod[i].getName() + ";and the i is:"
                        + i);
            }
            //
            Field[] allFields = clsShow.getFields();
            for (i = 0; i < allFields.length; i++) {
                Log.e("Field name", allFields[i].getName());
            }
        } catch (SecurityException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


        @SuppressWarnings("unchecked")
        static public boolean autoBond(Class btClass,BluetoothDevice device,String strPin) throws Exception {   

        Method autoBondMethod = btClass.getMethod("setPin",
                new Class[] { byte[].class });
        Boolean result = (Boolean) autoBondMethod.invoke(device,
                new Object[] { strPin.getBytes() });
        return result;

    }

}


This code is useful for Automatically pair and connect Bluetooth Devices without user-interaction.

Please be share improving Answer... `