子线程创建处理程序的作用是什么?

时间:2017-09-11 14:56:10

标签: android handler android-looper

1.我在子线程中创建处理程序时遇到问题

public class Main4Activity extends Activity {

private TextView mTextView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView = (TextView) findViewById(R.id.text_view);
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            @SuppressLint("HandlerLeak") Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Toast.makeText(Main4Activity.this, "handler msg", Toast.LENGTH_SHORT).show();
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mTextView.setText("100");
                }
            };
            handler.sendEmptyMessage(1);
            Looper.loop();
        }
    }.start();
}

} 上面的代码会崩溃。

Process: com.example.hellokai.kotlindemo, PID: 27485
                                               android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
                                                   at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6986)
                                                   at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1074)
                                                   at android.view.View.requestLayout(View.java:19889)
                                                   at android.view.View.requestLayout(View.java:19889)
                                                   at android.view.View.requestLayout(View.java:19889)
                                                   at android.view.View.requestLayout(View.java:19889)
                                                   at android.support.constraint.ConstraintLayout.requestLayout(ConstraintLayout.java:1959)
                                                   at android.view.View.requestLayout(View.java:19889)
                                                   at android.widget.TextView.checkForRelayout(TextView.java:7369)
                                                   at android.widget.TextView.setText(TextView.java:4480)
                                                   at android.widget.TextView.setText(TextView.java:4337)
                                                   at android.widget.TextView.setText(TextView.java:4312)
                                                   at com.example.hellokai.kotlindemo.Main4Activity$1$1.handleMessage(Main4Activity.java:40)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at com.example.hellokai.kotlindemo.Main4Activity$1.run(Main4Activity.java:45)
2.我知道在主线程中更新ui,在主线程中创建处理程序,然后在子线程中发送消息给处理程序,可以更新Ui。

3.我的问题是在子线程中创建的处理程序的作用是什么?我们什么时候需要这样做?场景有什么用?

希望有人能解决我的困惑!

2 个答案:

答案 0 :(得分:1)

  
      
  1. 我在子线程中创建处理程序时遇到问题。
  2.   

您正在从后台线程更新ui。

例如,您可以从线程发送消息并更新ui,如

private Handler handler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(Main4Activity.this.getApplicationContext(), "handler msg", Toast.LENGTH_SHORT).show();

        mTextView.setText((String)msg.obj);
    }
};

然后

  new Thread() {
        @Override
        public void run() {

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = Message.obtain(); // Creates an new Message instance
            msg.obj = "Hello";
            handler.sendMessage(msg);

        }
    }.start();

或者如果您只是想延迟,则不需要线程,循环和睡眠,如pskink https://developer.android.com/reference/android/os/Handler.html

的评论中所述
  
      
  1. 我知道在主线程中更新ui,在主线程中创建处理程序,然后在子线程中发送消息给   处理程序可以更新Ui。
  2.   

是的你是对的你可以在ui线程上创建处理程序,你可以从线程发送消息并更新你的ui

  
      
  1. 我的问题是在子线程中创建的处理程序的作用是什么?
  2.   

处理程序与线程的循环器相关联。如果你在ui线程中有一个处理程序,它与它相关联。在你的情况下,你将它放在一个线程中,因此处理程序与那些线程looper相关联。

  

我们什么时候需要这样做?场景有什么用?

当您想要从backgroud线程到ui线程或从ui线程到后台线程进行通信时。

答案 1 :(得分:0)

您的代码

new Thread() {
    @Override
    public void run() {
        Looper.prepare();
        @SuppressLint("HandlerLeak") Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Toast.makeText(Main4Activity.this, "handler msg", Toast.LENGTH_SHORT).show();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mTextView.setText("100");
            }
        };
        handler.sendEmptyMessage(1);
        Looper.loop();
    }
}.start();

可以重写使用Android apis:

new Handler(getMainLooper()).postDelayed(
new Runnable() {
    @Override
    public void run() {
                Toast.makeText(Main4Activity.this, "handler msg", Toast.LENGTH_SHORT).show();
                mTextView.setText("100");
        }
    }
}, 200);

另请注意,您的主要问题是您在Runnable中创建了一个已经在工作线程中的Handler,您也可以在onCreate中尽早创建它。

相关问题