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.私の質問は、子スレッドで作成されたハンドラーの役割は何ですか? いつそれをする必要がありますか?シーンの使用は何ですか?
誰かが私の混乱を解決してくれることを願っています!</p>