5.20

所花时间(包括上课):2.5

打码量(行):250

博客量(篇):1

了解到知识点:学习Looper

 

package com.example.myapp;

 

import android.os.Handler;

import android.os.Looper;

import android.os.Message;

 

public class BackgroundThread extends Thread {

 

    private Handler handler;

 

    @Override

    public void run() {

        // 在后台线程中创建 Looper

        Looper.prepare();

 

        // 创建 Handler 对象,处理消息

        handler = new Handler() {

            @Override

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                // 处理消息逻辑

                // 可以根据消息类型执行不同的操作

            }

        };

 

        // 启动消息循环

        Looper.loop();

    }

 

    public Handler getHandler() {

        return handler;

    }

}

package com.example.myapp;

 

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.widget.TextView;

 

import androidx.appcompat.app.AppCompatActivity;

 

public class MainActivity extends AppCompatActivity {

 

    private TextView messageTextView;

    private BackgroundThread backgroundThread;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        messageTextView = findViewById(R.id.messageTextView);

 

        // 创建后台线程实例

        backgroundThread = new BackgroundThread();

        backgroundThread.start();

 

        // 获取后台线程的 Handler 对象,并发送消息

        Handler handler = backgroundThread.getHandler();

        Message message = handler.obtainMessage();

        message.obj = "Hello from BackgroundThread!";

        handler.sendMessage(message);

    }

}

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

 

    <TextView

        android:id="@+id/messageTextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Waiting for message..."

        android:textSize="18sp"

        android:layout_centerInParent="true" />

 

</RelativeLayout>

posted @ 2024-05-20 18:52  赵千万  阅读(4)  评论(0编辑  收藏  举报