我正在将蓝牙设备连接到我的Android应用程序。在onItemCLick上我得到了设备并调用了createBond()。它正在连接但是立即断开连接。下面是我用于连接的代码 -
private boolean createBond(BluetoothDevice btDevice)throws Exception {
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mBluetoothAdapter.cancelDiscovery();
String bDevice = (String) mLvDevices.getItemAtPosition(position);
String str = bDevice.substring(bDevice.length() - 17);
BluetoothDevice device = null;
for(int i=0; i<= mBTDeviceList.size()-1; i++) {
if(mBTDeviceList.get(i).getAddress().toString().equalsIgnoreCase(str)) {
device = mBTDeviceList.get(i);
}
}
Toast.makeText(getActivity().getApplicationContext(), device.toString(), Toast.LENGTH_LONG).show();
BaseActivity baseActivity = (BaseActivity) getActivity();
baseActivity.setBtDevice(device);
if(device != null) {
try {
isBonded = createBond(device);
} catch (Exception e) {
e.printStackTrace();
}
}
}