简体   繁体   English

关于Android runnable的问题

[英]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? 我想知道为什么我们需要使用runnable来设置TextView的文本? Thanks! 谢谢!

    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/ 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. 在这种情况下,只有一个线程可以在UI上执行操作 - UI线程。 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. 一旦你自己开始一个新的线程并且你想让它做一些与UI相关的事情(比如更新serverStatus文本字段的文本),你必须在UI线程上做。 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. 在这种情况下,UI线程有一个处理程序,它在创建服务器线程时作为参数发送。 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. 每次需要更新UI时,它都会向UI线程发送一条消息,该线程会定期检查新消息并执行附加到它们的Runnables。

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 这是另一个链接(示例)可能会帮助您更好地理解它: 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. UI(在本例中为edittext)只能在Uithread中更新。 Runnable gets you back to the UI thread. Runnable让你回到UI线程。 Reference: http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable ) 参考: http//developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM