1

I've seen a lot of questions about this subject but i'm really not happy with any answer.

What i want its to have a class ConnectionController implements Runnable that is responsible for opening the conection to server, read and write messages to it and have to be instantiated since the beginning of the application through the end.

I have a class MainActivity extends from Activity that onCreate it will instantiate a ConnectionController object.

That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

Because connectionController is a Thread i cannot access to elements (CalledFromWrongThreadException (Only the original thread that created a view hierarchy can touch its views).

What do you recommend to use? I saw solution with async tasks, handlers, myUIRunnable but i didn't understand what is the best solution for this situation.

Thanks in advance.

Eduardo Pinheiro
  • 3,409
  • 3
  • 30
  • 39

1 Answers1

1

That connectionController has to change some fields on MainActivity (and eventually in another activities), like status conections ImageView for example, or even received messages TextView.

No, it does not. It needs to arrange for those things to be changed. Since you elected to make a "controller" be a thread for some reason, the controller cannot change those UI elements itself.

What do you recommend to use?

Use post() on a View. Or, use runOnUiThread() on an Activity. Or, use a Handler.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • My question was what the best to use. Anyway i opted for the Handler. Thanks – Eduardo Pinheiro Mar 04 '12 at 13:33
  • @Edu: There is no "best", at least in the abstract. Any of those are equally "best" on their own. Whether one makes sense given the *rest* of your app, only you can determine, because we only know what you wrote here. – CommonsWare Mar 04 '12 at 13:51