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. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android(安卓)Stuido优化速度
  2. android中获得屏幕、视图、任务栏、状态
  3. Android(安卓)关闭虚拟按钮、底部导航条
  4. android 水平滚动源码
  5. Android获取手机短信和通话记录及通讯录
  6. Android(安卓)Tombstone/Crash的log分析
  7. Android(安卓)NDK Camera2小结
  8. 魅族手机 Android5 获取手机联系人返回空
  9. android的帮助、about、关于作者、HELP等
  10. Android--为TextView添加边框