我编写了一个android应用程序,使用蓝牙从外部传感器获取数据.它在索尼爱立信XPERIA上运行良好,但在HTC Hero上却无法运行(它可以找到外部设备,但无法从中获取任何数据),我想知道为什么.经过网上研究后,我仍然没有发现任何线索.
有人在HTC上有类似的蓝牙问题吗?
解决方法:
如果我没记错的话,HTC手机在某个API级别(也许是2.1或更低版本)存在或[有]问题.分辨率是反射.
参考
Disconnect a bluetooth socket in Android
Service discovery failed exception using Bluetooth on Android
解
而不是使用
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
采用
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
使用特定的API级别在某些HTC手机上获取BluetoothSocket.
解决方案扩展
我最近有一个必须解决这个问题的应用程序,我不喜欢在非HTC手机上使用它,因此我有条件检查HTC,如果为true,则使用反射,否则不要使用.
public BTConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the given BluetoothDevice
if (isAnHTCDevice())
{
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
}
catch (Exception e)
{
Log.e(BCTAG, "Error at HTC/createRfcommSocket: " + e);
e.printStackTrace();
handler.sendMessage(handler.obtainMessage(MSG_BT_LOG_MESSAGE, "Exception creating htc socket: " + e));
}
}
else
{
try
{
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (Exception e)
{
Log.e(BCTAG, "Error at createRfcommSocketToServiceRecord: " + e);
e.printStackTrace();
handler.sendMessage(handler.obtainMessage(MSG_BT_LOG_MESSAGE, "Exception creating socket: " + e));
}
}
mmSocket = tmp;
}
isAnHTCDevice():
public boolean isAnHTCDevice()
{
String manufacturer = android.os.Build.MANUFACTURER;
if (manufacturer.toLowerCase().contains("htc"))
return true;
else
return false;
}