<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="开始" android:id="@+id/btn1" android:onClick="startThread"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv1"/> </LinearLayout>
通过点击按钮,让子线程1写字符串,传输到Message中,再在子线程1中用主线程的handle对象去发送消息,再让主线程判断是否为子线程1发过来的,再设置为Textview的文字。
package com.example.a20221130_threadhandler; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btn; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = findViewById(R.id.btn1); textView = findViewById(R.id.tv1); } //让子线程去运行的方法,获取字符串 private String GetString(){ String string=""; StringBuilder stringBuilder=new StringBuilder(); for(int i=0;i<10;i++){ stringBuilder.append("sb" + i); } //沉睡4秒 try { Thread.sleep(4000); }catch (InterruptedException i){ i.printStackTrace(); } string=stringBuilder.toString(); return string; } //获取主线程的Handle Handler handler=new Handler(Looper.myLooper()){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); //判断获取到的Message信息是哪个编号 if(msg.what==0){ String data = (String) msg.obj; textView.setText(data); Toast.makeText(MainActivity.this, "主线程收到", Toast.LENGTH_SHORT).show(); } } }; public void startThread(View view) { new Thread(new Runnable() { @Override //run()方法里面是子线程运行的,其他都是主线程,包括start() public void run() { String s = GetString(); //创建一个Message类 Message message=new Message(); message.what=0; message.obj=s; //让主线程的handler对象发送信息MessageQueue即可 handler.sendMessage(message); } }).start(); Toast.makeText(this, "任务完成", Toast.LENGTH_SHORT).show(); } }