Do some Android UI stuff in non-UI thread
Is there a way to do UI changes in a开发者_如何学运维 non-UI thread? Short question.
Either use Handler or use below code
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Ui Stuff here
}
});
There are many way to do this, use AsyncTask or Threads. Short answer.
Hint: the UI stuff can be done in the pre-postExecute/runOnUiThread/Handler class
If you dont want to use an AsyncTask, try the observer pattern with an inner class (ResponseHandler) in your main activity, sorry I couldnt get the formatting right but im sure you get the idea
public class WorkerThread extends Observable implements Runnable {
public void run() {
try {
DoSomething();
String response = "Doing something";
setChanged();
notifyObservers( response );
DoSomethingElse();
String response = "Doing something else";
setChanged();
notifyObservers( response );
}
catch (IOException e) {
e.printStackTrace();
}
}
private void DoSomething(){
}
private void DoSomethingElse(){
}
public class MainActivity{
public class ResponseHandler implements Observer {
private String resp;
public void update (Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
//Write message to UI here ie System.out.println("\nReceived Response: "+ resp );
//or EditText et = (EditText)findViewById(R.id.blah);
// blah.SetText(resp);
}
}
}
private void doStuffAndReportToUI(){
final WorkerThread wt = new WorkerThread();
final ResponseHandler respHandler = new ResponseHandler();
wt.addObserver( respHandler );
Thread thread = new Thread(wt);
thread.start();
}
Check out the Handler class. Or take a look at these similar questions:
Update UI from Thread
Handling UI code from a Thread
updating the ui from thread using audiotrack
Try to explore runOnUIThread()
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
I tried +tmho answer, but it still gives this error:
E/AndroidRuntime(****): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I finally end up combinning it with +ingsaurabh way, like that:
private class ResponseHandler implements Observer, Runnable {
Activity act;
public ResponseHandler(Activity caller) {
act = caller;
}
@Override
public void update (Observable obj, Object arg) {
act.runOnUiThread(this);
}
@Override
public void run() {
//update UI here
}
}
thanks both of you.
精彩评论