i have tried implement object in android work in own thread (i not want make handler public, want wrap sentmessage method own public api). has public methods pass data object. object associated activity lifecycle (onresume, onpause). use looper , handler, not pure java thread infinite loop. want start worker thread on resume , stop working on pause callback. object has wait new message infinitely. code below:
public class threadingobject { private mythread thread; public threadingobject() {} public void onresume() { thread = new mythread(); thread.startworking(); } public void onpause() { thread.stopworking(); } public void setmessage(object object) { message msg = new message(); msg.obj = object; thread.handler.sendmessage(msg); } protected void work(object object) { //do object in own thread } private class mythread extends thread { public handler handler; @override public void run() { looper.prepare(); handler = new handler() { @override public void handlemessage(message msg) { threadingobject.this.work((string[]) msg.obj); } }; looper.loop(); } public void startworking() { start(); } public void stopworking() { handler.getlooper().quit(); } } } is correct implementation? receive warning: "sending message handler on dead thread". there issue not see?
it implementation:
public class threadingobject { private handlerthread thread; private handler handler; private handler.callback handlercallback = new handler.callback() { @override public boolean handlemessage(message msg) { work(msg.obj); return true; } }; public threadingobject() {} public void onresume() { thread = new handlerthread("surfaceview handlerthread"); thread.start(); handler = new handler(thread.getlooper(), handlercallback); } public void onpause() { if(thread != null) { thread.quit(); thread = null; } handler = null; } public void setmessage(object object) { message msg = new message(); msg.obj = object; handler.sendmessage(msg); } protected void work(object obj) { //working } }
Comments
Post a Comment