安卓蓝牙无法连接

2024-04-21

我遇到这个问题已经有一段时间了,但一直无法解决。

我有一个 Android 应用程序,它将所有配对的设备放在列表视图中。当您单击列表项之一时,它将发起连接到该蓝牙设备的请求。

我可以毫无问题地获取设备列表及其地址。 问题是,一旦我尝试连接,我就会在 socket.connect(); 上收到 IOException 异常。

错误信息如下:“连接读取失败,套接字可能关闭或超时,读取ret:-1”

这是我的代码。ANY如有建议,我们将不胜感激。我对此很困惑。

仅供参考:“onEvent”方法是一个简化回调的库......该部分有效。 当用户单击列表项时,此方法被称为“公共无效onEvent(EventMessage.DeviceSelected事件)"

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) { }
    }
}

这是我的日志猫。很短。

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 秒的间隔


果冻豆蓝牙堆栈与其他版本明显不同。

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

安卓蓝牙无法连接 的相关文章

随机推荐

  • 如何从 PyQt4 中的 QVariant 取回我的 python 对象?

    我正在创建一个子类QAbstractItemModel要显示在QTreeView My index and parent 函数创建QModelIndex使用QAbstractItemModel继承功能createIndex并为其提供row
  • 带有排序指示符的表标题

    我正在尝试在 angularjs 中创建一个支持排序的简单网格 我无法弄清楚如何为每个列正确创建排序指示器 然后将其绑定到sortoptions在控制器上 这样当它们改变时 排序指示器也会改变 我的 WIP 在这里 http plnkr c
  • Django:有什么方法可以在不诉诸魔法的情况下更改 FileField 的“upload_to”属性?

    请参阅这篇博文 http scottbarnham com blog 2007 07 31 uploading images to a dynamic path with django 它已经很旧了 所以也许事情已经改变了 但在我的实验中他
  • 如何在javascript中删除二维数组中的行

    如何在 JavaScript 中使用行号删除二维数组中的行 如果我想删除第4行中的所有元素那么该怎么做呢 以下是如何使用删除行的示例splice https developer mozilla org en US docs Web Java
  • 在 JavaScript 中设置星期几

    我正在使用phonegap localNotifications 插件 它指定我可以设置每周发生一次通知 然而 看来 javascript 日期对象只有 getDay 并不是 setDay 我有一个 json 对象 表示我想设置重复的星期几
  • Azure Function 中的 Html 到 Pdf 库

    Azure功能显然还不支持System Drawing 沙箱信息 https github com projectkudu kudu wiki Azure Web App sandbox win32ksys user32gdi32 rest
  • Google OR-Tools TSP 返回几个解决方案

    我最近一直致力于使用 Google 的 OR Tools 寻找最佳路线以外的内容 我找到了一个仓库中的示例 https github com google or tools blob master examples dotnet cshar
  • 测量缩放画布上的文本

    我一直在努力处理文本测量和缩放画布 当画布未缩放时 getTextBounds 和measureText 可提供准确的结果 但是 当缩放画布时 这两种方法都无法提供与打印文本的实际大小相匹配的结果 为了进行测试 我使用以下 onDraw 方
  • `typedef typename Foo::Bar Bar' 的模板声明

    我在声明模板类型时遇到了很大的困难 如下所示 include
  • 自 iOS 7 发布以来,将不会为添加到配置文件的设备安装临时 iOS .ipa 文件

    我有一个 iOS 应用程序 我已经开发了一段时间了 最初 iOS 开发帐户中有大约 8 台设备 广告版本是通过 Hockey App 准备和分发的 没有任何问题 最近 我们添加了更多设备 但由于某种原因 临时版本不会安装在这些设备上 但继续
  • 如何实现让 UITableView 设置其单元格的插图而不在整个表格上设置插图?

    我有一个UITableViewCell内容延伸到其所有边缘 我在多个表格中使用此单元格 其中需要不同的插图 即一个表格将其从左侧插入 8 个点 另一个表格将其插入 20 个点 我想缩进父级中的单元格UITableView代码 也许cellF
  • 使用 Shopify 管理 API 创建产品

    我第一次开始使用 React 和 Node js 构建私有 Shopify 应用程序 该应用程序的目的是监听 添加到购物车 按钮 单击该按钮后 它应该使用 Shopify 产品 API 在 Shopify 后端中创建自定义产品 我在基本 J
  • 如何从 Github 隐藏 .env 文件

    我在 Rails 项目中使用 dotenv 来存储 API 密钥 我的 gemfile 中有 dotenv gem 在应用程序的根目录中创建了一个 env 并在其中列出了我的 API 密钥 但是 当我推送到 github 时 我注意到 en
  • IE 未在 TLS 相互身份验证中发送客户端证书

    我正在尝试与第三方 API 建立 TLS 相互身份验证 客户端证书配置良好 当我尝试通过 Chrome 访问端点 url 时 它工作正常 Chrome 要求在消息框中确认证书 当我这样做时 页面会显示其内容 当我尝试使用 IE 执行同样的操
  • Routes.rb vsrack-rewrite vs nginx/apache 重写规则

    我的应用程序的前一个版本中的遗留 URL 有数十条重写规则 我看到三个选择 只需在路由文件 config routes rb 中添加 匹配 行 Use 机架重写 https github com jtrupiano rack rewrite
  • 用于展平嵌套列表的递归生成器

    我是一名编程新手 在理解我的 Python 教科书 Magnus Lie Hetland 的 Beginning Python 中的示例时遇到了一些困难 该示例是一个递归生成器 旨在展平嵌套列表的元素 具有任意深度 def flatten
  • Apple 听写 - 在应用程序中使用

    有什么方法可以在本机 Apple 应用程序中利用 Apple 的听写语音转文本功能吗 你的问题有点模糊 最好先知道你尝试使用或做什么 或者你想要实现什么目标 更常见的是关键字识别 API 但可以用于此目的的语音识别 API 是张开耳朵 ht
  • iOS Storyboard:ViewController 外部和场景顶部的视图(第一响应者和退出框之间)

    我很难理解为什么你可以把UIViews之外的UIViewController在故事板上 以及它的用例可能是什么 例如 在故事板上我可以添加UIToolbar UIAcitivtyIndicator and UIProgressView那是在
  • 如何在类模板中使用文件范围的命名空间声明?

    C 10 介绍文件范围的命名空间 https learn microsoft com en us dotnet csharp language reference proposals csharp 10 0 file scoped name
  • 安卓蓝牙无法连接

    我遇到这个问题已经有一段时间了 但一直无法解决 我有一个 Android 应用程序 它将所有配对的设备放在列表视图中 当您单击列表项之一时 它将发起连接到该蓝牙设备的请求 我可以毫无问题地获取设备列表及其地址 问题是 一旦我尝试连接 我就会