android - How to create listener to the server on thread that was created on service? -
i have android service creates new thread.
@override public int onstartcommand(intent intent, int flags, int startid) { t = new connectionthread(); t.start(); return service.start_not_sticky; }
on thread i'm opening socket connection , keeping alive. looks this
@override public void run() { try { inetaddress serveraddr = inetaddress.getbyname(server_ip); socket = new socket(serveraddr, serverport); } catch (ioexception e) { e.printstacktrace(); } }
on thread have method can send json message server. call service , service command called fragment (on buttonclick) , works fine.
public string sendjson() { jsonobject messagejson = new jsonobject(); jsonobject mjson = new jsonobject(); try { mjson.put("type", "readytobind"); messagejson.put("deviceid", "mydeviceid"); messagejson.put("allowfastbind", true); mjson.put("message", messagejson); } catch (jsonexception e) { e.printstacktrace(); } printwriter out = null; try { out = new printwriter(new bufferedwriter(new outputstreamwriter(socket.getoutputstream())), true); out.println(mjson); } catch (ioexception e) { e.printstacktrace(); } return message2; }
but main problem server giving response in 3 seconds. means can give response instantly or wait 0-3 seconds , give different response.
how should implement listener server? should listen commands recieved server , react application (change current fragment ui).
i tried create second thread on sendjson() method
mthread = new connectionthread2ndlevel(socket); mthread.start(); long start = system.currenttimemillis(); long end = start + 3 * 1000; // 3 seconds * 1000 ms/sec while (system.currenttimemillis() < end){ message2 = mthread.getmessage(); }
and on thread run() method read , on getmessage() return recieved message.
scanner = new scanner(socket.getinputstream()); message2thread = scanner.nextline();
but freezes application , user nothing can during time. not i've got response server (maybe got response , on while loop read blank line , return back.
so please, can give me advice or example how in right way? great server listener recieve message , instantly initiate changes on fragment (ui).
Comments
Post a Comment