mat*_*hes 95 android serial-port bluetooth android-4.3-jelly-bean
目前我正试图在我的Nexus 7(2012)上使用Android 4.3(Build JWR66Y,我猜第二次4.3更新)打开BluetoothSocket时遇到一个奇怪的异常.我已经看到了一些相关的帖子(例如/sf/ask/955386141/),但似乎没有提供此问题的解决方法.此外,正如在这些线程中所建议的那样,重新配对没有帮助,并且不断尝试连接(通过愚蠢的循环)也没有任何效果.
我正在处理嵌入式设备(noname OBD-II车载适配器,类似于http://images04.olx.com/ui/15/53/76/1316534072_254254776_2-OBD-II-BLUTOOTH-ADAPTERSCLEAR-CHECK-ENGINE-灯光与你的电话-Oceanside.jpg).我的Android 2.3.7手机连接没有任何问题,同事的Xperia(Android 4.1.2)也可以使用.另一个Google Nexus(我不知道'One'或'S',但不是'4')也因Android 4.3而失败.
这是连接建立的片段.它在自己的Thread中运行,在Service中创建.
private class ConnectThread extends Thread {
private static final UUID EMBEDDED_BOARD_SPP = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter adapter;
private boolean secure;
private BluetoothDevice device;
private List<UUID> uuidCandidates;
private int candidate;
protected boolean started;
public ConnectThread(BluetoothDevice device, boolean secure) {
logger.info("initiliasing connection to device "+device.getName() +" / "+ device.getAddress());
adapter = BluetoothAdapter.getDefaultAdapter();
this.secure = secure;
this.device = device;
setName("BluetoothConnectThread");
if (!startQueryingForUUIDs()) {
this.uuidCandidates = Collections.singletonList(EMBEDDED_BOARD_SPP);
this.start();
} else{
logger.info("Using UUID discovery mechanism.");
}
/*
* it will start upon the broadcast receive otherwise
*/
}
private boolean startQueryingForUUIDs() {
Class<?> cl = BluetoothDevice.class;
Class<?>[] par = {};
Method fetchUuidsWithSdpMethod;
try {
fetchUuidsWithSdpMethod = cl.getMethod("fetchUuidsWithSdp", par);
} catch (NoSuchMethodException e) {
logger.warn(e.getMessage());
return false;
}
Object[] args = {};
try {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice deviceExtra = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
Parcelable[] uuidExtra = intent.getParcelableArrayExtra("android.bluetooth.device.extra.UUID");
uuidCandidates = new ArrayList<UUID>();
for (Parcelable uuid : uuidExtra) {
uuidCandidates.add(UUID.fromString(uuid.toString()));
}
synchronized (ConnectThread.this) {
if (!ConnectThread.this.started) {
ConnectThread.this.start();
ConnectThread.this.started = true;
unregisterReceiver(this);
}
}
}
};
registerReceiver(receiver, new IntentFilter("android.bleutooth.device.action.UUID"));
registerReceiver(receiver, new IntentFilter("android.bluetooth.device.action.UUID"));
fetchUuidsWithSdpMethod.invoke(device, args);
} catch (IllegalArgumentException e) {
logger.warn(e.getMessage());
return false;
} catch (IllegalAccessException e) {
logger.warn(e.getMessage());
return false;
} catch (InvocationTargetException e) {
logger.warn(e.getMessage());
return false;
}
return true;
}
public void run() {
boolean success = false;
while (selectSocket()) {
if (bluetoothSocket == null) {
logger.warn("Socket is null! Cancelling!");
deviceDisconnected();
openTroubleshootingActivity(TroubleshootingActivity.BLUETOOTH_EXCEPTION);
}
// Always cancel discovery because it will slow down a connection
adapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
// Close the socket
try {
shutdownSocket();
} catch (IOException e2) {
logger.warn(e2.getMessage(), e2);
}
}
}
if (success) {
deviceConnected();
} else {
deviceDisconnected();
openTroubleshootingActivity(TroubleshootingActivity.BLUETOOTH_EXCEPTION);
}
}
private boolean selectSocket() {
if (candidate >= uuidCandidates.size()) {
return false;
}
BluetoothSocket tmp;
UUID uuid = uuidCandidates.get(candidate++);
logger.info("Attempting to connect to SDP "+ uuid);
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
uuid);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
uuid);
}
bluetoothSocket = tmp;
return true;
} catch (IOException e) {
logger.warn(e.getMessage() ,e);
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
代码失败了bluetoothSocket.connect().我得到了一个java.io.IOException: read failed, socket might closed, read ret: -1.这是GitHub上的相应源代码:https://github.com/android/platform_frameworks_base/blob/android-4.3_r2/core/java/android/bluetooth/BluetoothSocket.java#L504
它通过readInt()调用,从https调用://github.com/android/platform_frameworks_base/blob/android-4.3_r2/core/java/android/bluetooth/BluetoothSocket.java#L319
使用的套接字的某些元数据转储导致以下信息.这些在Nexus 7和我的2.3.7手机上完全相同.
Bluetooth Device 'OBDII'
Address: 11:22:33:DD:EE:FF
Bond state: 12 (bonded)
Type: 1
Class major version: 7936
Class minor version: 7936
Class Contents: 0
Contents: 0
Run Code Online (Sandbox Code Playgroud)
我有一些其他OBD-II适配器(更多的扩展),他们都工作.有没有机会,我错过了什么或者这可能是Android中的错误?
mat*_*hes 125
我终于找到了解决方法.神奇的是在引擎盖下隐藏的BluetoothDevice类(见https://github.com/android/platform_frameworks_base/blob/android-4.3_r2/core/java/android/bluetooth/BluetoothDevice.java#L1037).
现在,当我收到例外,我实例化一个后备BluetoothSocket,类似于下面的源代码.如您所见,createRfcommSocket通过反射调用隐藏方法.我不知道为什么隐藏这个方法.源代码定义它public好像......
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
fallbackSocket.connect();
Run Code Online (Sandbox Code Playgroud)
connect()那么不会再失败了.我还遇到了一些问题.基本上,这有时会阻塞并失败.重新启动SPP-设备(插上腾飞/插入)帮助在这种情况下.有时我也在之后得到另一个配对要求connect()即使设备已粘合.
更新:
这是一个完整的类,包含一些嵌套类.对于真正的实现,这些可以作为单独的类进行.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class BluetoothConnector {
private BluetoothSocketWrapper bluetoothSocket;
private BluetoothDevice device;
private boolean secure;
private BluetoothAdapter adapter;
private List<UUID> uuidCandidates;
private int candidate;
/**
* @param device the device
* @param secure if connection should be done via a secure socket
* @param adapter the Android BT adapter
* @param uuidCandidates a list of UUIDs. if null or empty, the Serial PP id is used
*/
public BluetoothConnector(BluetoothDevice device, boolean secure, BluetoothAdapter adapter,
List<UUID> uuidCandidates) {
this.device = device;
this.secure = secure;
this.adapter = adapter;
this.uuidCandidates = uuidCandidates;
if (this.uuidCandidates == null || this.uuidCandidates.isEmpty()) {
this.uuidCandidates = new ArrayList<UUID>();
this.uuidCandidates.add(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
}
}
public BluetoothSocketWrapper connect() throws IOException {
boolean success = false;
while (selectSocket()) {
adapter.cancelDiscovery();
try {
bluetoothSocket.connect();
success = true;
break;
} catch (IOException e) {
//try the fallback
try {
bluetoothSocket = new FallbackBluetoothSocket(bluetoothSocket.getUnderlyingSocket());
Thread.sleep(500);
bluetoothSocket.connect();
success = true;
break;
} catch (FallbackException e1) {
Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
} catch (InterruptedException e1) {
Log.w("BT", e1.getMessage(), e1);
} catch (IOException e1) {
Log.w("BT", "Fallback failed. Cancelling.", e1);
}
}
}
if (!success) {
throw new IOException("Could not connect to device: "+ device.getAddress());
}
return bluetoothSocket;
}
private boolean selectSocket() throws IOException {
if (candidate >= uuidCandidates.size()) {
return false;
}
BluetoothSocket tmp;
UUID uuid = uuidCandidates.get(candidate++);
Log.i("BT", "Attempting to connect to Protocol: "+ uuid);
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(uuid);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
}
bluetoothSocket = new NativeBluetoothSocket(tmp);
return true;
}
public static interface BluetoothSocketWrapper {
InputStream getInputStream() throws IOException;
OutputStream getOutputStream() throws IOException;
String getRemoteDeviceName();
void connect() throws IOException;
String getRemoteDeviceAddress();
void close() throws IOException;
BluetoothSocket getUnderlyingSocket();
}
public static class NativeBluetoothSocket implements BluetoothSocketWrapper {
private BluetoothSocket socket;
public NativeBluetoothSocket(BluetoothSocket tmp) {
this.socket = tmp;
}
@Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
@Override
public String getRemoteDeviceName() {
return socket.getRemoteDevice().getName();
}
@Override
public void connect() throws IOException {
socket.connect();
}
@Override
public String getRemoteDeviceAddress() {
return socket.getRemoteDevice().getAddress();
}
@Override
public void close() throws IOException {
socket.close();
}
@Override
public BluetoothSocket getUnderlyingSocket() {
return socket;
}
}
public class FallbackBluetoothSocket extends NativeBluetoothSocket {
private BluetoothSocket fallbackSocket;
public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
super(tmp);
try
{
Class<?> clazz = tmp.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[] {Integer.valueOf(1)};
fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
}
catch (Exception e)
{
throw new FallbackException(e);
}
}
@Override
public InputStream getInputStream() throws IOException {
return fallbackSocket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return fallbackSocket.getOutputStream();
}
@Override
public void connect() throws IOException {
fallbackSocket.connect();
}
@Override
public void close() throws IOException {
fallbackSocket.close();
}
}
public static class FallbackException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public FallbackException(Exception e) {
super(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*ima 91
好吧,我的代码有同样的问题,这是因为Android 4.2蓝牙堆栈已经改变了.所以我的代码在android <4.2的设备上正常运行,在其他设备上我得到了着名的异常"读取失败,套接字可能关闭或超时,读取ret:-1"
问题在于socket.mPort参数.使用时创建套接字socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);,mPort获取整数值" -1 ",此值似乎不适用于android> = 4.2,因此您需要将其设置为" 1 ".坏消息是createRfcommSocketToServiceRecord只接受UUID作为参数而不是mPort我们必须使用其他方法.@matthes发布的答案也适用于我,但我简化了它:socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);.我们需要使用两个套接字attribs,第二个作为后备.
所以代码是(用于连接到ELM327设备上的SPP):
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter.isEnabled()) {
SharedPreferences prefs_btdev = getSharedPreferences("btdev", 0);
String btdevaddr=prefs_btdev.getString("btdevaddr","?");
if (btdevaddr != "?")
{
BluetoothDevice device = btAdapter.getRemoteDevice(btdevaddr);
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // bluetooth serial port service
//UUID SERIAL_UUID = device.getUuids()[0].getUuid(); //if you don't know the UUID of the bluetooth device service, you can get it like this from android cache
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {Log.e("","Error creating socket");}
try {
socket.connect();
Log.e("","Connected");
} catch (IOException e) {
Log.e("",e.getMessage());
try {
Log.e("","trying fallback...");
socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
socket.connect();
Log.e("","Connected");
}
catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
}
else
{
Log.e("","BT device not selected");
}
}
Run Code Online (Sandbox Code Playgroud)
tob*_*ora 13
首先,如果您需要与蓝牙2.x设备通信,此文档说明:
提示:如果要连接蓝牙串行板,请尝试使用众所周知的SPP UUID 00001101-0000-1000-8000-00805F9B34FB.但是,如果您要连接到Android对等设备,请生成您自己的唯一UUID.
我认为它不会起作用,但只有用00001101-0000-1000-8000-00805F9B34FB它取代UUID 才有效.然而,这个代码似乎处理的SDK版本的问题,您只需更换功能device.createRfcommSocketToServiceRecord(mMyUuid);与tmp = createBluetoothSocket(mmDevice);定义以下方法之后:
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, mMyUuid);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(mMyUuid);
}
Run Code Online (Sandbox Code Playgroud)
源代码不是我的,但来自这个网站.
小智 7
我有与此处描述的症状相同的症状.我可以连接一次到蓝牙打印机,但后续连接失败,"套接字关闭",无论我做什么.
我发现这里描述的变通方法是必要的,这有点奇怪.经过我的代码后,我发现我忘了关闭套接字的InputStream和OutputSteram而没有正确终止ConnectedThreads.
我使用的ConnectedThread与此处的示例相同:
http://developer.android.com/guide/topics/connectivity/bluetooth.html
请注意,ConnectThread和ConnectedThread是两个不同的类.
无论什么类启动ConnectedThread都必须在线程上调用interrupt()和cancel().我在ConnectedTread.cancel()方法中添加了mmInStream.close()和mmOutStream.close().
正确关闭线程/流/套接字后,我可以创建新的套接字而没有任何问题.
好吧,我实际上发现了这个问题.
尝试使用连接的大多数人socket.Connect();都会调用异常Java.IO.IOException: read failed, socket might closed, read ret: -1.
在某些情况下,它还取决于您的蓝牙设备,因为有两种不同类型的蓝牙,即BLE(低能耗)和经典.
如果您想检查蓝牙设备的类型,请输入以下代码:
String checkType;
var listDevices = BluetoothAdapter.BondedDevices;
if (listDevices.Count > 0)
{
foreach (var btDevice in listDevices)
{
if(btDevice.Name == "MOCUTE-032_B52-CA7E")
{
checkType = btDevice.Type.ToString();
Console.WriteLine(checkType);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在努力解决这个问题,但从今天起我就找到了问题所在.不幸的是,@matthes的解决方案仍然存在一些问题,正如他已经说过的那样,但这是我的解决方案.
目前我在Xamarin Android工作,但这也适用于其他平台.
解
如果有多个配对设备,则应删除其他配对设备.因此,请仅保留您要连接的那个(请参阅右图).
在左图中,您看到我有两个配对设备,即"MOCUTE-032_B52-CA7E"和"Blue Easy".这是问题,但我不知道为什么会出现这个问题.也许蓝牙协议试图从另一个蓝牙设备获取一些信息.
然而,这些socket.Connect();作品现在很好,没有任何问题.所以我只是想分享这个,因为这个错误真的很烦人.
祝好运!
小智 6
你把
registerReceiver(receiver, new IntentFilter("android.bleutooth.device.action.UUID"));
"蓝牙"拼写为"bleutooth".
小智 6
在较新版本的Android上,我收到此错误,因为当我尝试连接到套接字时,适配器仍在发现。即使我在Bluetooth适配器上调用了cancelDiscovery方法,我也必须等到通过动作BluetoothAdapter.ACTION_DISCOVERY_FINISHED调用了BroadcastReceiver的onReceive()方法的回调。
等待适配器停止发现后,套接字上的connect调用就成功了。
如果有人在使用 Kotlin 时遇到问题,我必须按照已接受的答案进行一些修改:
fun print(view: View, text: String) {
var adapter = BluetoothAdapter.getDefaultAdapter();
var pairedDevices = adapter.getBondedDevices()
var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
if (pairedDevices.size > 0) {
for (device in pairedDevices) {
var s = device.name
if (device.getName().equals(printerName, ignoreCase = true)) {
Thread {
var socket = device.createInsecureRfcommSocketToServiceRecord(uuid)
var clazz = socket.remoteDevice.javaClass
var paramTypes = arrayOf<Class<*>>(Integer.TYPE)
var m = clazz.getMethod("createRfcommSocket", *paramTypes)
var fallbackSocket = m.invoke(socket.remoteDevice, Integer.valueOf(1)) as BluetoothSocket
try {
fallbackSocket.connect()
var stream = fallbackSocket.outputStream
stream.write(text.toByteArray(Charset.forName("UTF-8")))
} catch (e: Exception) {
e.printStackTrace()
Snackbar.make(view, "An error occurred", Snackbar.LENGTH_SHORT).show()
}
}.start()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
| 归档时间: |
|
| 查看次数: |
117138 次 |
| 最近记录: |