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());
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。