Android蓝牙接受()/连接()与已配对的设备
我无法通过蓝牙连接两个Android设备,只有在配对之前才会发生此问题。我运行一个作为服务器,另一个作为客户端。Android蓝牙接受()/连接()与已配对的设备
这里的东西在服务器端的顺序:
- 检查各种蓝牙状态(可用适配器,启用等)。
- 用我选择的预定义的UUID调用listenUsingRfcommWithServiceRecord()。
- 请求使设备可发现
- 由于可发现异步发生,我调用accept()并等待传入连接。
在客户端:
- 检查各种蓝牙状态(适配器可用,启用等)。
- getBondedDevices()中的每个设备,我将getName()与服务器名称进行比较。如果匹配,请跳到步骤6.
- 开始BT发现
- 对于每个发现的设备(请注意2a的配对设备不会在此显示),请将设备名称与服务器名称进行比较。如果存在匹配,则转到步骤6。
- 取消发现
- 在那个从步骤2中找到的装置,呼叫createRfcommSocketToServiceRecord()与已在服务器侧使用的相同的预先定义的UUID。
- 调用connect()并等待它返回连接的套接字。
当客户端和服务器之前从未配对时,上述过程对我来说工作得非常好。但是,在Android注册到设备列表中后,它们将不可避免地在connect()/ accept()阶段超时。
我一直在寻找了两天的解决方案,并已尝试了不少事情,包括这一个: Connecting to a already paired Bluetooth device
反射方法不为我工作的。看起来connect()会立即返回,但是当我尝试getOutputStream()时,我得到一个异常。在accept()方面,它甚至不记录有人试图连接。我认真需要一些帮助或指示让设备建立连接,一旦他们以前配对。
下面是有关设备的一些信息:
- 我测试服务器和客户端上的两个LG G2X手机。
- 他们都在Android 2.3.3上运行,这对应于API级别10.
- 同样,上述工作在我在设置中手动解除设备配对后运行。
谢谢你提前。我大约在2周内使用Android和蓝牙,因此如果您看到任何缺少的步骤或最佳做法,请将它们指出。
在客户端,当我尝试连接绑定设备时,我只是在我在BluetoothAdapter.getBondedDevices()
中找到的BluetoothDevice上调用它。这是行不通的。
为了正确地建立了蓝牙连接,我不得不做类似下面的一些伪代码:Bluetooth Chat Service:
BluetoothDevice bonded = a device from BluetoothAdapter.getBondedDevices();
BluetoothDevice actual = BluetoothAdapter.getRemoteDevice(bonded.getAddress());
BluetoothSocket socket = actual.createRfcommSocketToServiceRecord(SOME_UUID);
socket.connect();
我按照完全相同的蓝牙聊天例子来到这个答案。为什么它不能在getBondedDevices()
的设备上工作是超出我的。也许有更熟悉Android的人可以回答这个问题。
看看这个例子:http://developer.android.com/resources/samples/BluetoothChat/index.html。
这可以解释蓝牙设备如何连接和传输信息。
private static BluetoothSocket mSocket;
BluetoothDevice selectDevice = null;
void connectDevice(){
if(mSocket == null) {
//Log.d(TAG, "Socket is null");
UUID SPP_UUID = UUID
.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
Set<BluetoothDevice> bondedDevices = BluetoothAdapter
.getDefaultAdapter().getBondedDevices();
//Log.d(TAG, "Size: " + bondedDevices.size());
/**
* Select your divice form paired devices
*/
for (BluetoothDevice bluetoothDevice : bondedDevices) {
selectDevice = bluetoothDevice;
//Log.d(TAG, bluetoothDevice.getName()+" "+bluetoothDevice.getAddress());
}
if(selectDevice.getBondState() == selectDevice.BOND_BONDED) {
//Log.d(TAG, selectDevice.getName());
try {
mSocket = selectDevice.createInsecureRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e1) {
// TODO Auto-generated catch block
//Log.d(TAG, "socket not created");
e1.printStackTrace();
}
try {
mSocket.connect();
} catch (IOException e) {
try {
mSocket.close();
//Log.d(TAG, "Cannot connect");
} catch (IOException e1) {
//Log.d(TAG, "Socket not closed");
e1.printStackTrace();
}
}
}
getRemoteDevice不是一个静态方法,你怎么总是调用它 – raja 2013-02-07 14:06:19
你(几乎?)要使用BluetoothAdapter.getDefaultAdapter()作为BluetoothAdapter。以上只是伪代码,所以你不能简单地复制和粘贴。 – 2013-02-08 17:21:52
伟大的文章,这实际上是有道理的,因为该设备是一个参考,并将陈旧。适配器将始终处于最新状态。 – Cookster 2013-07-19 22:55:18