【发布时间】:2011-03-24 17:57:50
【问题描述】:
我目前正在开发一个通过蓝牙连接到仪器的 Android 应用程序,需要编写字符串命令并接收返回的字符串响应。目前,我通过 Wi-Fi 为 TCP/IP 进行连接/读/写工作,现在正在尝试实现蓝牙。但我遇到了一些障碍。我一直在网上搜索,试图找到类似的例子,但没有任何运气。我一直在使用 Android 开发者资源示例:蓝牙聊天作为我的主要参考点。
我当前的代码似乎可以工作。然后它会在连接点引发服务发现失败异常。我正在使用DeviceListActivity 类来发现和选择我想要连接的设备。它返回一个ActivityResult,然后我的蓝牙类等待它处理它,然后连接到它。下面的代码几乎与蓝牙聊天应用程序相同。
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!m_BluetoothAdapter.isEnabled())
{
m_BluetoothAdapter.enable();
}
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = m_BluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
}
else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
这是我的连接函数:
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private void connect(BluetoothDevice device) {
m_Device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}
catch (IOException e) {
}
m_Socket = tmp;
m_BluetoothAdapter.cancelDiscovery();
try {
// This is a blocking call and will only return on a
// successful connection or an exception
m_Socket.connect();
}
catch (IOException e) {
try {
m_Socket.close();
}
catch (IOException e2) {
}
return;
}
}
希望,无论我做错什么都很简单,但恐怕从来没有那么容易。这是我第一次做任何蓝牙开发,也许我做错了什么……但我不确定为什么会出现服务发现失败的异常。
您可以随时在手机上手动配对/查找设备...确实需要密码,但我认为这不是我遇到的问题。
【问题讨论】: