如何实现android蓝牙自动配对连接

本文介绍了一种在Android平台上实现蓝牙设备自动配对的方法。通过使用反射调用BluetoothDevice类中的隐藏方法createBond()和setPin()实现了蓝牙配对过程,并通过cancelBondProcess()和cancelPairingUserInput()取消了配对提示框。文章提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对.

上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了

我就开始查找怎么关闭这个蓝牙配对提示框,后面还是伟大的android源码帮助了我。

在源码 BluetoothDevice 
类中还有两个隐藏方法

cancelBondProcess()和cancelPairingUserInput()

这两个方法一个是取消配对进程一个是取消用户输入

<receiver android:name=".BluetoothConnectActivityReceiver" >
    <intent-filter>
        <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
    </intent-filter>
</receiver>

public class BluetoothConnectActivityReceiver extends BroadcastReceiver
{

 String strPsw = "0";

 @Override
 public void onReceive(Context context, Intent intent)
 {
  // TODO Auto-generated method stub
  if (intent.getAction().equals(
    "android.bluetooth.device.action.PAIRING_REQUEST"))
  {
   BluetoothDevice btDevice = intent
     .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

   // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
   // device.setPin(pinBytes);
   Log.i("tag11111", "ddd");
   try
   {
    ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手机和蓝牙采集器配对
    ClsUtils.createBond(btDevice.getClass(), btDevice);
    ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
   }
   catch (Exception e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }


 }
}

<b>/************************************ 蓝牙配对函数 * **************/
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
  */
 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
  */
 static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
   throws Exception
 {
  Method removeBondMethod = btClass.getMethod("removeBond");
  Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
  return returnValue.booleanValue();
 }

 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;

 }

 // 取消用户输入
 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();
 }

 // 取消配对
 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();
  }
 }
}</b>

<b>public static boolean pair(String strAddr, String strPsw)
 {
  boolean result = false;
  BluetoothAdapter bluetoothAdapter = BluetoothAdapter
    .getDefaultAdapter();

  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");
    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();
   } //

  }
  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 result;
 }</b>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值