//第一次链接须要输入密码,这个是弹起弹窗的方式
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(); } }