TxA*_*xAg 49 java android bluetooth
我目前正在研究一种通过蓝牙连接到仪器的Android应用程序,需要编写字符串命令并接收字符串响应.目前我通过Wi-Fi进行TCP/IP连接/读/写工作,现在尝试实现蓝牙.但我遇到了一些障碍.我一直在网上搜索试图找到类似的东西的例子,并没有运气.我一直在使用Android开发人员资源示例:蓝牙聊天作为我的主要参考点.
我当前的代码似乎工作..然后它会在连接点抛出Service Discovery Failed异常.我正在使用DeviceListActivity该类来发现和选择我想要连接的设备.它返回anActivityResult,然后我的蓝牙类等待它处理它,然后连接到它.下面的代码几乎与蓝牙聊天应用程序相同.
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的连接功能:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
希望无论我做错什么都很简单,但我担心这从未如此简单.这是我第一次进行任何蓝牙开发,也许我正在做一些明显的错误...但我不知道为什么我得到服务发现失败的异常.
您可以在手机上手动配对/查找设备......它确实需要密码,但我不认为这是我遇到的问题.
TxA*_*xAg 93
三天后,我想通过一些非常有用的帖子弄明白了.
我不得不替换:
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Run Code Online (Sandbox Code Playgroud)
有:
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
Run Code Online (Sandbox Code Playgroud)
并且它有效!
Muz*_*ant 13
从API 15开始,您可以使用以下方法:
尝试使用类的getUuids()方法的返回值替换您的UUID BluetoothDevice.对我有用的是这样的:
UUID uuid = bluetoothDevice.getUuids()[0].getUuid();
BluetoothSocket socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
Run Code Online (Sandbox Code Playgroud)
这样做的原因是不同的设备支持不同的UUID,并且通过使用getUuids获取设备的UUID,您支持所有功能和设备.
另一个有趣的新方法(自API 14起支持)是:BluetoothHealth.getConnectionState.没试过但看起来很有希望......
| 归档时间: |
|
| 查看次数: |
57385 次 |
| 最近记录: |