Android Bluetooth Stream Non-blocking Communication Tutorial
16lz
2021-01-23
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()); } }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer