最近在做一个项目用到蓝牙,但是所有蓝牙的操作必须要后台进行,于是网上搜了下找到了方法。。首先需要下面3个方法,通过反射去操作

     

     static public boolean createBond(Class btClass, BluetoothDevice btDevice)throws Exception {Method createBondMethod = btClass.getMethod("createBond");Log.i("life", "createBondMethod = " + createBondMethod.getName());Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);return returnValue.booleanValue();}static public boolean setPin(Class btClass, BluetoothDevice btDevice,String str) throws Exception {Boolean returnValue = null;try {Method removeBondMethod = btClass.getDeclaredMethod("setPin",new Class[] { byte[].class });returnValue = (Boolean) removeBondMethod.invoke(btDevice,new Object[] { str.getBytes() });Log.i("life", "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 blocke.printStackTrace();}return returnValue;}// 取消用户输入static public boolean cancelPairingUserInput(Class btClass,BluetoothDevice device) throws Exception {Method createBondMethod = btClass.getMethod("cancelPairingUserInput");// cancelBondProcess()Boolean returnValue = (Boolean) createBondMethod.invoke(device);Log.i("life", "cancelPairingUserInputreturnValue = " + returnValue);return returnValue.booleanValue();}
     然后监听蓝牙配对的广播  匹配“android.bluetooth.device.action.PAIRING_REQUEST”这个action
  然后分辨调用上面的setPin(mDevice.getClass(), mDevice, "1234"); // 手机和蓝牙采集器配对   createBond(mDevice.getClass(), mDevice);   cancelPairingUserInput(mDevice.getClass(), mDevice);
   其中上面的mDevice是你要去连接的那个蓝牙的对象 , 1234为配对的pin码

更多相关文章

  1. android NoticificationManager状态栏操作
  2. Android:如何给 ScrollView 添加滑块滚动条
  3. Android(安卓)多线程编程
  4. Android(安卓)最优轮循(心跳策略)探究实践
  5. Android(安卓)操作系统的设计与实现--框架
  6. Android(安卓)WebView 中的 Html 网页定位操作
  7. Android(安卓)RxJava 实际应用讲解:联想搜索优化
  8. 关于对于google的android手机操作系统的一点想法!
  9. [Android]AndroidDesign中ActionBar探究1

随机推荐

  1. 模态框简单编写
  2. 视口、定位和模态框
  3. android pull解析
  4. Android日历(Calendar,dataPicker)
  5. 浅谈android的selector背景选择器
  6. Android(安卓)本地广播动作
  7. Android(安卓)Handler机制 - handleMessa
  8. Android通过Alpha实现渐变效果的几个方法
  9. Android(安卓)最火的快速开发框架XUtils
  10. Android学习(2)EditView属性