multithreading - Update Android UI from a thread in another class -
i've seen few questions on here asking similar questions, i've not yet seen suitable answer. many people have asked how update ui thread, they're in same class ui.
what i'm trying update ui thread has been created in class. i've seen of suggestions, such async, handlers, runnable, etc... i've having real problem implementing them in separate classes.
i'm trying maintain ui class minimal , deal interactions gui, such when user presses button. now, i've created new thread, in new class, connects bluetooth device, want alter button in ui thread beingness 'connect' button 'disconnect' button (i.e. alter button creating bluetooth socket closing it).
what general way this? thinking of wrong , should have in 1 class? right way interact between 'main' ui class , other classes/threads?
ideally want able other ui interactions, solution allows other ui changes outside of ui class great!
what i'm trying update ui thread has been created in class. i've seen of suggestions, such async, handlers, runnable, etc... i've having real problem implementing them in separate classes.
generally goal recommend use:
asynctask
intentservice
resultreceiver
i don't think tricky. absolutely not. if have separated class(es) , not inner class(es) in activity
class recommend utilize constructor pass context, widgets, whatever want , in right methods(which allows ui update) update ui
.
i'm doing because when have clean classes(so ui class have ui implementations , logic positioned separately).
example:public class taskexample extends asynctask<void, integer, void> { private context c; private button b; public taskexample(context c, button b) { this.c = c; this.b = b; } protected void doinbackground(void... params) { // work if (issomethingconnected) { publishprogress(constants.is_connected); } homecoming null; } public void onprogressupdate(integer... params) { switch (params[0]) { case constants.is_connected: b.settext("connected"); break; case constants.another_constant: // work break; } } }
usage:
public class main extends activity implements view.onclicklistener { private button b; public void oncreate(bundle b) { super.oncreate(b); // initialise widgets , set listeners appropriate widgets } public void onclick(view v) { switch(v.getid()) { case r.id.connectbtn: startworker(); break; } } private void startworker() { taskexample te = new taskexample(this, b); te.execute(); } }
android multithreading asynchronous runnable handlers
No comments:
Post a Comment