在Android Studio中配对蓝牙设备
我正在创建一个应该通过蓝牙连接到特定设备的应用程序。在Android Studio中配对蓝牙设备
我希望我的应用程序能够与此设备连接,而不管它是否已配对。
现在我有这个
private void findDevice() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals(DEVICE_NAME)) {
bluetoothDevice = device;
deviceFound = true;
break;
}
}
}
}
不过这个功能只连接到配对设备。 如果我的设备尚未配对,我想将它配对。 不知道该怎么做。
有人可以给我任何建议吗?
第一次请求BLUETOOTH_ADMIN
权限。
然后,让您的设备可发现:
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
然后创建一个广播接收器从系统中收听到行动:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Found, add to a device list
}
}
};
,并开始注册这个BoardcastReceiver搜索设备:
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
设备来自的BroadcastReceiver到一个列表后,从列表中createBond()
这种选择您的设备:
public 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();
}
然后使用上面的代码与绑定设备进行管理。
男士,非常感谢,似乎合法。 但是BroadcastReciever有问题。 Android Studio说我无法解析符号'BroadcastReciever'。 IM在谷歌搜索的答案,但无法找到一个:( – Kirchhoff1415
@ Kirchhoff1415什么问题 – nhoxbypass
好,我知道,我缺少 进口android.content.BroadcastReceiver; 部分 – Kirchhoff1415
您是否要求BLUETOOTH_ADMIN权限? – nhoxbypass
是的,我请求 – Kirchhoff1415
你有没有尝试过:https://stackoverflow.com/questions/14228289/android-pair-devices-via-bluetooth-programmatically – nhoxbypass