java - How to use Connected Thread in multiple activites -
i newbie in android. first i've written application connects device via bluetooth, sends , receives data, using socket , connected thread. while using 1 activity works great, receive data using handler. started make application multiple activities, made special class socket connection , connected thread. send data activity, don't know how receive answer (how make handler in many activities, or alternative use). possibly me , write lines of code, should add.
thanks.
here thread:
private class connectedthread extends thread { private final bluetoothsocket mmsocket; private final inputstream mminstream; private final outputstream mmoutstream; public connectedthread(bluetoothsocket socket) { mmsocket = socket; inputstream tmpin = null; outputstream tmpout = null; try { tmpin = socket.getinputstream(); tmpout = socket.getoutputstream(); } catch (ioexception e) {} mminstream = tmpin; mmoutstream = tmpout; } public void run() { byte[] buffer = new byte[256]; int bytes; while(true) { try { bytes = mminstream.read(buffer); byte[] readbuf = (byte[]) buffer; string strincom = new string(readbuf, 0, bytes); // here need method send data activity } catch (ioexception e) { break; } } } public void write(string message) { byte[] msgbuffer = message.getbytes(); try { mmoutstream.write(msgbuffer); } catch (ioexception e) { } } }
well, 1 thing can use of interface,
for example:
public class connectedthread extends thread { // declare interface in class body public static interface callbacklistener { public void onreceived(string msg); } private final bluetoothsocket mmsocket; private final inputstream mminstream; private final outputstream mmoutstream; private callbacklistener listener = null; // then, want use class must implement // interface public connectedthread(bluetoothsocket socket, callbacklistener alistener) { this.listener = alistener; ... and in run method of thread this:
// here need method send data activity if (listener != null) { listener.onreceived(strincom); } and when create class, this:
bluetoothsocket socket = null; /* * create bluetoothsocket here bluetoothsocket socket = new bluetoothsocket(...); */ connectedthread conthread = new connectedthread(socket, new connectedthread.callbacklistener() { @override public void onreceived(string msg) { // here you'll receive string msg // keep in mind receive call // in connectedthread's context, not ui thread } });
Comments
Post a Comment