12.29

 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 Handler handler;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        messageTextView = findViewById(R.id.messageTextView);

 

        // 创建 Handler 对象,处理消息更新 UI

        handler = new Handler(getMainLooper()) {

            @Override

            public void handleMessage(Message msg) {

                super.handleMessage(msg);

                // 处理消息,更新 UI

                String message = (String) msg.obj;

                messageTextView.setText(message);

            }

        };

 

        // 模拟后台线程发送消息到主线程更新 UI

        new Thread(new Runnable() {

            @Override

            public void run() {

                try {

                    Thread.sleep(2000); // 模拟耗时操作

                    String message = "Hello from background thread!";

                    Message msg = Message.obtain();

                    msg.obj = message;

                    handler.sendMessage(msg); // 发送消息到主线程更新 UI

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }).start();

    }

}

<?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-12-29 20:48  赵千万  阅读(2)  评论(0编辑  收藏  举报