【发布时间】:2012-06-11 20:04:42
【问题描述】:
我在任何地方都可以找到适用于我的蓝牙适配器的“getBondedDevices()”方法。但是,我有我的平板电脑和另一个蓝牙设备坐在我旁边,我不知道如何实际让设备显示在绑定设备列表中。
【问题讨论】:
我在任何地方都可以找到适用于我的蓝牙适配器的“getBondedDevices()”方法。但是,我有我的平板电脑和另一个蓝牙设备坐在我旁边,我不知道如何实际让设备显示在绑定设备列表中。
【问题讨论】:
在蓝牙术语中,“bonded”和“paired”基本上是同义词(官方说,配对过程会产生bond,但大多数人可以互换使用它们)。为了将您的设备添加到该列表中,您必须完成 发现 过程,即一台设备如何搜索并找到另一台设备,然后将两者配对在一起。
您实际上可以作为用户从设备设置中执行此操作,但如果您希望在应用程序的上下文中这样做,您的过程可能看起来像这样:
BluetoothDevice.ACTION_FOUND 和BluetoothAdapter. ACTION_DISCOVERY_FINISHED 注册BroadcastReceiver
BluetoothAdapter.startDiscovery() 开始发现
BluetoothAdapter.cancelDiscovery()。BluetoothSocket 和connect()。如果设备尚未绑定,这将启动配对并可能会显示一些系统 UI 以获取 PIN 码。connect() 方法实际上也打开了套接字链接,当它返回而不抛出异常时,两个设备已连接。getInputStream()和getOutputStream()读写数据了。基本上,您可以检查绑定设备列表以快速访问外部设备,但在大多数应用程序中,您将结合执行此操作和真正的发现,以确保您始终可以连接到远程设备,无论用户做什么。如果设备已绑定,您只需执行第 5-7 步即可进行连接和通信。
有关更多信息和示例代码,请查看Android SDK Bluetooth Guide 的“发现设备”和“连接设备”部分。
HTH
【讨论】:
createRfcommSocketToServiceRecord() 方法用于从设备生成套接字对象。
connect(),如指南的“作为客户端连接”示例中所示。当connect()成功返回时,您可以使用getInputStream()和getOutputStream()开始传输数据。
getBondedDevices()(如果已经配对)或BroadcastReceiver 回调中获得BluetoothDevice。在后一种情况下,设备本身作为 Intent 中的额外内容传递回 onReceive() 方法。
API 级别 19 及以上您可以在要连接的 BluetoothDevice 实例上调用 createBond()。 您需要一些权限才能发现和列出可见设备
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
发现和列出设备的代码:
bluetoothFilter.addAction(BluetoothDevice.ACTION_FOUND);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
bluetoothFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(bluetoothReceiver, bluetoothFilter);
private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_FOUND");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devicesList.add((device.getName() != null ? device.getName() : device.getAddress()));
bluetoothDevicesAdapter.notifyDataSetChanged();
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_STARTED");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_FINISHED");
getActivity().unregisterReceiver(bluetoothReceiver);
}
}
};
只需在所选设备上调用 createBond()。
【讨论】: