Android——主线程给子线程发送消息——子线程有自己的looper

发布时间 2024-01-06 20:24:44作者: 小白龙白龙马

xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:text="Send Message" />

</LinearLayout>

 

 

 

 

main:

package com.example.myapplication;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = handler.obtainMessage();
                msg.what = 100;
                handler.sendMessage(msg);
                Log.d("TTTT", "sendMessage:" + Thread.currentThread().getName());
            }
        });

        WorkerThread wt = new WorkerThread();
        wt.start();
    }


    class WorkerThread extends Thread {
        @Override
        public void run() {
            super.run();
            Looper.prepare();
            handler = new Handler(Looper.myLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Log.d("TTTT", "handleMessage:" + Thread.currentThread().getName());
                    int i = msg.what;
                    Log.d("TTTT", "收到了消息对象:" + i);
                }
            };
            Looper.loop();
        }
    }
}