蓝牙

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

posted @ 2017-06-07 13:54  烟花易冷心易碎  阅读(278)  评论(0编辑  收藏  举报