android 蓝牙隐藏对话框 后台配对

     最近在做一个项目用到蓝牙,但是所有蓝牙的操作必须要后台进行,于是网上搜了下找到了方法。。首先需要下面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 block
			e.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码

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值