A question about Android runnable
I saw a piece of code online. I am wondering why we need to use runnable to set text of TextView? Thanks!
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
@Override
public void run() {
serverS开发者_JS百科tatus.setText("Connected.");
}
});
http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/
This application is multi-threaded, isn't it? In that case, only one thread can do operations on UI - the UI thread. If you don't manually create new threads, then you don't have to worry about this. Once you start a new thread yourself and you want it to do something UI related (like updating text of serverStatus text-field), you have to do it on UI thread. Not obeying this rule will result in an exception.
Handlers are used as a way of passing messages between threads. In this case, the UI thread has a handler, which was sent as a parameter when server-thread was created. Every time it needs to update UI, it posts a message to the UI thread, which periodically checks for new messages and executes Runnables attached to them.
Here's another link (with example) that might help you understand it a bit better: http://developer.android.com/guide/appendix/faq/commontasks.html#threading
That piece of code is in server thread. UI (in this case edittext) can only be updated in the Uithread. Runnable gets you back to the UI thread. Reference: http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
精彩评论