藍牙

    //第一次鏈接須要輸入密碼,這個是彈起彈窗的方式
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();        }    }
相關文章
相關標籤/搜索