蓝牙

    //第一次连接需要输入密码,这个是弹起弹窗的方式
private void requestConnectWindow(BluetoothDevice remoteDevice) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
if (!mBTadapter.isEnabled()){//本地蓝牙设备是否开启没开启则开启
mBTadapter.enable();
}
if (mBTadapter.isDiscovering()){//本地蓝牙设备是否正在扫描,正在扫描则停止扫描
mBTadapter.cancelDiscovery();
}

Boolean returnValue = false;
//利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
returnValue = (Boolean) createBondMethod.invoke(remoteDevice);
Log.i(TAG, "第一次连接蓝牙请求弹窗:"+remoteDevice.getName());
}
//自动连接已经保存的设备
private void connectAlreadySaveDevice(BluetoothDevice remoteDevice) {
if (!mBTadapter.isEnabled()){//本地蓝牙设备是否开启没开启则开启
mBTadapter.enable();
}
if (mBTadapter.isDiscovering()){//本地蓝牙设备是否正在扫描,正在扫描则停止扫描
mBTadapter.cancelDiscovery();
}
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";//UUid唯一标示符,可以生成,也可以写死,这里就先写死了
UUID uuid = UUID.fromString(SPP_UUID);
try {
BluetoothSocket btSocket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
btSocket.connect();
Log.i(TAG, "已经连接蓝牙设备:"+remoteDevice.getName());
} catch (IOException e) {
e.printStackTrace();
}
}


    //取消蓝牙配对
private void unpairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
//反射设置弹窗的配对码
public void setBluetoothPairingPin(BluetoothDevice device) {
String string = "1234";
byte[] pinBytes = string.getBytes();
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();
}
}
 

转载于:https://www.cnblogs.com/lizhanqi/p/6956655.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值