【问题标题】:How to handle InputStream and OutputStream via Bluetooth in Android如何在 Android 中通过蓝牙处理 InputStream 和 OutputStream
【发布时间】:2016-03-24 13:19:44
【问题描述】:

我正在开发一个 Android 应用程序来处理由 Arduino 制成的警报系统。 我必须处理从 Arduino 和 OutputStream 到 Arduino 的 InputStream。首先,我使用一个线程来初始化蓝牙套接字的连接并且它可以工作,但是在线程内部我必须调用一种服务/线程,它可以让我处理来自和到 Arduino 的流,但我不知道如何做。 事实是,如果有流,假设服务必须连续监听,它必须在我想要的时候停止,而不是在一段时间后停止。谢谢您的帮助!下面是与蓝牙socket连接相关的代码:

    public class ConnectThread extends Thread {
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    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() {
        // Cancel discovery because it will slow down the connection
        while (!Thread.currentThread().isInterrupted()) {
            mBluetoothAdapter.cancelDiscovery();

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                    Log.i("Log", "Socket closed");
                    this.interrupt();
                    Log.i("Log", "Thread interrupted");
                } catch (IOException closeException) {

                }
            }

            //I think here I have to start a sort of Service/Thread..
        }
    }
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
            this.interrupt();
            Log.i("Log", "Thread interrupted");
        } catch (IOException e) { }
    }
}

【问题讨论】:

    标签: java android multithreading bluetooth


    【解决方案1】:

    我已经实现了一个类似的算法,我基本上是从BluetoothChatSample 复制的,例如,它也带有 android studio 示例。

    您可以在示例中看到所有概念,如何接收和发送字符串,它们还添加了权限、询问用户启用蓝牙的对话框等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      • 2013-04-25
      相关资源
      最近更新 更多