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,handler在主线程中创建,然后在子线程中发送消息给handler就可以更新ui了。
3.我的问题是子线程中创建的处理程序的作用是什么?我们什么时候需要这样做?场景有什么用?
希望有人能解决我的困惑!</p>