BluetoothAdapter
是系统的蓝牙适配器,常用功能有
1.开关蓝牙
2.扫描蓝牙
3.获取蓝牙基本信息,如mac地址,蓝牙名字,蓝牙状态
BluetoothAdapter初始化
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothAdapter打开功能
//是否打开
bluetoothAdapter.isEnabled();
//打开
bluetoothAdapter.enable();
//关闭
bluetoothAdapter.disable();
BluetoothAdapter搜索功能
//是否能被搜索
bluetoothAdapter.isDiscovering();
//开始搜索
bluetoothAdapter.startDiscovery();
//取消被发现
bluetoothAdapter.cancelDiscovery();
BluetoothAdapter蓝牙名字
//设置蓝牙名字
bluetoothAdapter.setName(name);
//获取蓝牙名字
bluetoothAdapter.getName();
配对功能
//配对
BluetoothDevice bDevice = bluetoothAdapter.getRemoteDevice(deviceInfo.getAddress());
bDevice.setPairingConfirmation(false);
if (bDevice.getBondState() == BluetoothDevice.BOND_NONE)
{
if (bDevice.createBond())
{
log.i("pairDevice", "Pairing ... ...");
}
else
{
log.i("pairDevice", "Pair error");
}
}
//取消配对
BluetoothDevice bDevice = bluetoothAdapter.getRemoteDevice(deviceInfo.getAddress());
int state = bDevice.getBondState();
log.d("unpairDevice", "state = " + state);
try
{
// 反射获取绑定状态
if (state == BluetoothDevice.BOND_BONDING)
{
Method method = BluetoothDevice.class.getMethod("cancelBondProcess");
method.invoke(bDevice);
}
else if (state == BluetoothDevice.BOND_BONDED || state == CommonConstant.BOND_SUCCESS)
{
disconnectDevice(deviceInfo);
bDevice.removeBond();
}
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}