3

我在网上看到一段代码。我想知道为什么我们需要使用 runnable 来设置 TextView 的文本?谢谢!

    while (true) {
    // listen for incoming clients
    Socket client = serverSocket.accept();
    handler.post(new Runnable() {
        @Override
        public void run() {
            serverStatus.setText("Connected.");
        }
    });

http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

4

2 回答 2

7

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

于 2010-12-21T23:27:36.947 回答
1

那段代码在服务器线程中。UI(在本例中为 edittext)只能在 Uithread 中更新。Runnable 让你回到 UI 线程。参考: http: //developer.android.com/reference/android/app/Activity.html#runOnUiThread (java.lang.Runnable )

于 2010-12-21T23:18:46.570 回答