Android - multithreading issues when changing activity -
i have main menu action bar. on create, run thread hits server current status. when complete, thread calls handler kicks off running thread cycles through items , uses handler call change test in actionbar. problem when change views, either android.view.windowleaked
or view not attached window manager
here sample code
public class mainmenuactivity extends protectedwithactionbaractivity{ private int status_counter; private final int result_status_loaded = 2000; private final int result_show_status = 2001; private currentstatusmodel currentstatus; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.mainmenu); actionbar footerbar = (actionbar)findviewbyid(r.id.footerbar); footerbar.settitle("currently connected " + preferenceshelper.getcurrentenvironment().name()); status_counter = 0; statusloadthread.start(); } thread statusloadthread = new thread() { @override public void run() { //set currentstatus data server } }; thread statusdisplaythread = new thread() { int sleep = 5000; boolean threaddone = false; public void done() { threaddone = true; } @override public void run() { while(true) { //pick message send handler //increment status_counter or reset 0 when out of bounds try { sleep(sleep); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } } }; private handler handler = new handler() { @override public void handlemessage(message msg) { switch(msg.what) { case result_status_loaded: statusdisplaythread.start(); break; case result_show_status: actionbar footerbar = (actionbar)findviewbyid(r.id.footerbar); string message = ((object[])msg.obj)[0].tostring(); onclicklistener listener = (onclicklistener)((object[])msg.obj)[1]; footerbar.settitle(message); footerbar.setontitleclicklistener(listener); break; case activitybase.result_error: break; } } }; }
i'm not sure if i'm doing wrong or if there blatantly obvious missing. needs happen threads need stop time change screens. should use thread.interrupt();
before starting next activity?
asynctasc allows implement doinbackground()
, thread can crank away @ task. similar functionality you'd thread
.
the real magic happens when override onpreexecute()
, onpostexecute()
, which both executed on ui thread. should keep getting messages activity not being attached.
edit - answer contains small code example asynctask
started.
Comments
Post a Comment