安卓蓝牙无法连接

12

我有一个Android应用程序,它将所有配对设备放入ListView中。当您点击其中一项列表项时,它会启动连接到蓝牙设备的请求。我可以轻松获取设备列表及其地址,但是一旦尝试连接,就会在socket.connect()上出现IOException。

错误消息如下:"connect read failed, socket might closed or timeout, read ret: -1"。以下是我的代码。欢迎任何建议。我已经卡住了。

提示:onEvent方法是简化回调的库……那部分起作用。当用户单击列表项时,将调用此方法“public void onEvent(EventMessage.DeviceSelected event)”。

public class EcoDashActivity extends BaseActivity {

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


private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 100;
private ArrayList<BluetoothDevice> mDevicesList;
private BluetoothDeviceDialog mDialog;
private ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();


@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

    mDevicesList = new ArrayList<BluetoothDevice>();

    // Register the BroadcastReceiver
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);

    setupBluetooth();
}

private void setupBluetooth() {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
        Toast.makeText(this, "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
    }

    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } else {
        searchForPairedDevices();
        mDialog = new BluetoothDeviceDialog(this, mDevicesList);
        mDialog.show(getFragmentManager(), "");
    }

}

private void searchForPairedDevices() {

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
    // If there are paired devices
    if (pairedDevices.size() > 0) {
        // Loop through paired devices
        for (BluetoothDevice device : pairedDevices) {
            // Add the name and address to an array adapter to show in a ListView
            mDevices.add(device.getName() + "\n" + device.getAddress());
            mDevicesList.add(device);
        }
    }
}


private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // Add the name and address to an array adapter to show in a ListView
            mDevicesList.add(device);
        }
    }
};


@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == RESULT_OK) {
            Toast.makeText(this, "BT turned on!", Toast.LENGTH_SHORT).show();
            searchForPairedDevices();

            mDialog = new BluetoothDeviceDialog(this, mDevicesList);
            mDialog.show(getFragmentManager(), "");
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}


public void onEvent(EventMessage.DeviceSelected event) {

    mDialog.dismiss();

    BluetoothDevice device = event.getDevice();

    ConnectThread connectThread = new ConnectThread(device);
    connectThread.start();
}


public class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        setName("ConnectThread");
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            Log.d("kent", "trying to connect to device");
            mmSocket.connect();
            Log.d("kent", "Connected!");
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                Log.d("kent", "failed to connect");

                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        Log.d("kent", "Connected!");
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

这是我的logcat。相当简短。

07-22 10:37:05.129: DEBUG/kent(17512): trying to connect to device
07-22 10:37:05.129: WARN/BluetoothAdapter(17512): getBluetoothService() called with no BluetoothManagerCallback
07-22 10:37:05.129: DEBUG/BluetoothSocket(17512): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[98]}
07-22 10:37:40.757: DEBUG/dalvikvm(17512): GC_CONCURRENT freed 6157K, 9% free 62793K/68972K, paused 7ms+7ms, total 72ms
07-22 10:38:06.975: DEBUG/kent(17512): failed to connect
07-22 10:38:06.975: DEBUG/kent(17512): read failed, socket might closed or timeout, read ret: -1

最后一行在try/catch的"Catch"部分,我只是记录错误信息。

请注意,在“尝试连接设备”和“连接失败”之间有约20秒的间隔。


哪个版本的Android?可能是堆栈问题,因为Jelly Bean有完全不同的蓝牙堆栈,请先取消配对并尝试重新配对,然后重试。 - Vrashabh Irde
@Slartibartfast,我目前正在使用4.2.2版本的Nexus 4进行工作。我会在问题中附上logcat日志。 - Kent Andersen
请检查我的答案,它应该会有所帮助。 - Vrashabh Irde
我会看一下。我可能需要几个小时才能测试它。 - Kent Andersen
2个回答

15

果冻豆蓝牙堆栈与其他版本有显着区别。

这可能会有所帮助:http://wiresareobsolete.com/wordpress/2010/11/android-bluetooth-rfcomm/

简而言之: UUID是一个值,必须指向嵌入式设备上发布的服务,而不是随机生成的。RFCOMM SPP连接您想要访问具有特定的UUID,它发布以标识该服务,并且当您创建套接字时,它必须匹配相同的UUID。

如果您的目标是4.0.3及以上设备,请使用fetchUuidsWithSdp()getUuids()查找所有已发布的服务及其关联的UUID值。为了向后兼容,请阅读文章。


GetUUIDs() 返回一个 ID 列表,你怎么知道哪个应该被使用? - Kent Andersen
我刚刚尝试了返回的每个UUID,但是问题仍然存在。 - Kent Andersen
你知道有没有完整的代码示例,我可以将其复制/粘贴到新应用程序中进行测试吗? - Kent Andersen
我看到有两个与你的问题相关的错误报告在Android上,看看这里是否有任何帮助或解决方法:https://code.google.com/p/android/issues/detail?id=41415和https://code.google.com/p/android/issues/detail?id=41110。 - Vrashabh Irde
3
我刚在“Note 2”设备上尝试了一下,代码运行得非常好。蓝牙立即连接成功。猜想这可能是Android 4.2.2或者Nexus 4的一个bug。我已经授予您奖励积分:)谢谢。 - Kent Andersen
1
我觉得值得注意的是,阅读此文的任何人都应该知道,我的代码正在连接到连接在我的汽车上的蓝牙适配器。我正在使用它来进行OBD2读数。我无法让应用程序与一个适配器连接,但最近我购买了另一个适配器,代码完美地运行了。因此,问题要么出在适配器上,要么是Android存在一个错误,不允许与某些设备通信。 - Kent Andersen

1
在第二次连接套接字后,我收到了相同的错误消息。我只是检查了套接字是否已经连接。
if(!mmSocket.isConnected())
            mmSocket.connect();

我正在 Android 4.4.2 (Moto G) 上进行测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接