Android BluetoothSocket.isConnected始终返回false

我正在尝试检测蓝牙设备当前是否使用API​​ 14或更高版本连接到 Android设备.看起来我应该可以使用BluetoothSocket.isConnected()方法,但无论我做了什么,到目前为止我只是因为任何事情而得到假回复,无论是否连接.

AndroidManifest包含以下行:

<uses-permission android:name="android.permission.BLUetoOTH" />
<uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />

<!-- Locale 4.x supports API 14 or greater. -->
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />

<uses-feature android:name="android.hardware.bluetooth" />

以及有问题的代码

protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    for (BluetoothDevice device : pairedDevices) {
        Log.i(Constants.LOG_TAG,String.format(Locale.US,"Device: %s connected: %b",device.getName(),isConnected(device))); //$NON-NLS-1$z
    }
}

private boolean isConnected(BluetoothDevice device) {
    BluetoothSocket socket = null;

    // Get a BluetoothSocket for a connection with the given BluetoothDevice
    UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    try {
        socket = device.createRfcommSocketToServiceRecord(SPP_UUID);
    } catch (IOException e) {
        Log.e(Constants.LOG_TAG,e.getMessage()); //$NON-NLS-1$z
        return false;
    }

    Log.i(Constants.LOG_TAG,socket.toString()); //$NON-NLS-1$z

    return socket.isConnected();
}

不会抛出任何错误,它只会在100%的时间内返回“false”.有什么东西我做得不对吗?

解决方法

我相信jkane001已经解决了他的问题,所以我希望这个答案可以帮助别人.

首先在套接字创建之后

socket = device.createRfcommSocketToServiceRecord(SPP_UUID);

你应该通过初始连接

socket.connect();

之后,您将能够使用socket.isConnected()检查连接状态

由于connect()方法没有阻塞,所以socket之后可能还没有连接.我建议使用这样的东西

while(!socket.isConnected() && triaL++ < 3){
    try {
        Thread.sleep(300);
    } catch (Exception e) {}
}

顺便说一句,我发现在一些Android设备上isConnected()总是返回false.在这种情况下,只是尝试写一些东西到socket并检查是否没有异常.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...