简体   繁体   English

Android蓝牙与远程设备连接

[英]android bluetooth connect with remote device

I want connect from my app in android device to remote device (paired). 我想从我的Android设备中的应用连接到远程设备(已配对)。 remote device is a module HC-05. 远程设备是模块HC-05。 my cod is : 我的鳕鱼是:

private 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 = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
        }
        mmSocket = tmp;
    }

    @Override
    public void run() {
        // Cancel discovery because it will slow down the connection
        ba.cancelDiscovery();

        try {
            mmSocket.connect();
        } catch (IOException e) {}

        // Do work to manage the connection (in a separate thread)
        // manageConnectedSocket(mmSocket);
        // connected();
        tv1.setText("connect");

    }

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

but get error in line mSocket.connect(). 但是在mSocket.connect()行中出现错误。 when run my app then get message : unfortunately (app name) has stopped. 当运行我的应用程序时,出现消息:不幸的是(应用程序名称)已停止。

please help. 请帮忙。

Do not silently ignore IOException . 不要默默地忽略IOException If you get IOException that means you. 如果得到IOException ,则意味着您。 for any reason, could not create socket. 由于任何原因,无法创建套接字。 mSocket then remains null and so you get the exception. 然后,mSocket保持为空,因此您将获得异常。 Might be you do not have bluetooth permission in manifest. 可能是您清单中没有蓝牙许可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM