android - get handler return null in LooperThread -
public class looperthread extends thread { private handler handler = null; public handler gethandler() { return handler; } @override public void run() { looper.prepare(); handler = new handler(); looper.loop(); } } class helper { private static looperthread databasethread = null; static { databasethread = new looperthread(); databasethread.start(); } public void postrunable(runnable r) { databasethread.gethandler().post(r); databasethread.gethandler().sendmessage(new message()); } } //ui thread. class uiactivity extends activity { private helper helper = new helper(); public void oncreate(bundle savedinstancestate) { helper.postrunnable(new runnable() { public void run() { //work asyn,like query db. } }); } }
sometimes call databasethread.gethandler().post(r);
,it return null,sometime not,why this?as usual,handler
should initial static block.
you times getting null handler
because calling databasethread.start();
in the static initializer ensures thread started @ point in future means thats creating race condition between handler getting created inside new thread , gethandler()
being called in old one. having thread background looper common pattern in android there class this.
first rid of looperthread
class , use sdk's handlerthread
instead.
your helper
class should
class helper { private static final handlerthread databasethread; private static final handler dbhandler; static { databasethread = new handlerthread("database thread"); databasethread.start(); // if have called handelerthread#start() // handlerthread#getlooper() block until looper initialized , looping dbhandler = new handler(databasethread.getlooper()); } public void postrunable(runnable r) { dbhandler.post(r); } }
Comments
Post a Comment