Android Bluetooth Stream Non-blocking Communication Tutorial

HiroshiFuu

This is a tutorial for Android to do non-blocking bluetooth socket communication. I am using 32feet Bluetooth library, but it should be the same if you were using other network socket communication that reply on inputstream mechanism.

In fact it is not asynchronous, however with a bit of threading magic, this system can work the way as asynchronous.

To move data from a background thread to the UI thread, use aHandlerthat’s running on the UI thread.
To get handler form a fragment, you could usethis.getView().getHandler().

BluetoothStreamListener bsl = new BluetoothStreamListener(handler, socket, message);
Thread messageListener = new Thread(bsl);
messageListener.start();

messaging system

private class MessageEventListener implements Runnable {

    private someUI ui;
    private String message;

    public MessageEventListener(someUI ui, String message) {
        this.ui= ui;
        this.message = message;
    }

    public void run() {
        ui.passMsg(message);
    }
}

stream listener

private class BluetoothStreamListener implements Runnable {

    private BluetoothSocket socket;
    private Handler handler;
    private someUI ui = null;

    public BluetoothStreamListener(BluetoothSocket socket, Handler handler, someUI ui) {
        this.socket = socket;
        this.handler = handler;
        this.ui = ui;
    }

    public void run() {
        int bufferSize = 2048;
        byte[] buffer = new byte[bufferSize];
        try {
            InputStream instream = socket.getInputStream();
            while (true) {
                if (instream.available() > 0) {
                    instream.read(buffer);
                    handler.post(new MessageEventListener(ui, buffer.toString()));
                    socket.getInputStream();
                }
            }
        } catch (IOException e) {
            Log.d("BluetoothStreamListener", e.getMessage());
        }
    }
}
阅读 1.3k

前端、后台、机器学习 in 私有云
-工作笔记 -Docker & Kubernetes -Node.JS & Django -Kafka & Spark & TensorFlow
49 声望
7 粉丝
0 条评论
49 声望
7 粉丝
文章目录
宣传栏