建立蓝牙连接时出错。回退

时间:2019-03-26 05:01:52

标签: android error-handling bluetooth

每当我的设备尝试连接超出范围或无法连接的设备时,我都会收到以下错误消息。如果建立连接,则应用正常运行。

首先让我告诉你,这个问题在这个站点被问了很多次。我经历了所有解决方案,但没有一个对我有用。

在我的情况下尝试在sock.connect上连接时发生错误。您会在我的蓝牙管理器中看到它。

蓝牙管理器的代码:

public class BluetoothManager {

private static final String TAG = BluetoothManager.class.getName();

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public static BluetoothSocket connect(BluetoothDevice dev) throws IOException {
    BluetoothSocket sock = null;
    BluetoothSocket sockFallback = null;

    Log.d(TAG, "Starting Bluetooth connection..");
    try {
        sock = dev.createRfcommSocketToServiceRecord(MY_UUID);
        sock.connect();
    } catch (Exception e1) {
        Log.e(TAG, "There was an error while establishing Bluetooth connection. Falling back..", e1);
        Class<?> clazz = sock.getRemoteDevice().getClass();
        Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
        try {
            Method m = clazz.getMethod("createRfcommSocket", paramTypes);
            Object[] params = new Object[]{Integer.valueOf(1)};
            sockFallback = (BluetoothSocket) m.invoke(sock.getRemoteDevice(), params);
            sockFallback.connect();
            sock = sockFallback;
        } catch (Exception e) {
            Log.e(TAG, "Couldn't fallback while establishing Bluetooth connection.");

        }
    }
    return sock;
}
}

日志:

E/com.quad14.obdnewtry.io.BluetoothManager: There was an error while establishing Bluetooth connection. Falling back..
    java.io.IOException: read failed, socket might closed or timeout, read ret: -1
        at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:738)
        at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:750)
        at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:375)
        at com.quad14.obdnewtry.io.BluetoothManager.connect(BluetoothManager.java:24)
        at com.quad14.obdnewtry.io.ObdGatewayService.startObdConnection(ObdGatewayService.java:116)
        at com.quad14.obdnewtry.io.ObdGatewayService.startService(ObdGatewayService.java:89)
        at com.quad14.obdnewtry.activity.MainActivity$16.onServiceConnected(MainActivity.java:1043)
        at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1453)
        at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1481)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6126)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

0 个答案:

没有答案