【线程】Android通过多线程在页面实时呈现(更新)内容

MainActivity.java

package com.example.thread;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {

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

        TextView tv = (TextView)findViewById(R.id.text2);

        final Handler handler = new Handler(){
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                //tv.setText(msg.arg1 + "");
                tv.setText((String)msg.obj);
            }
        };

        new Thread(){
            public void run(){
                int i = 0;
                while(true){
                    i++;
                    //tv.setText(String.valueOf(i));//子线程不能更新UI线程
                    Date date = new Date();
                    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :HH:mm:ss");
                    Message msg = Message.obtain();
                    msg.obj = dateFormat.format(date);
                    //msg.arg1 = i;
                    handler.sendMessage(msg);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

layout > activity_main.xml


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

androidx.constraintlayout.widget.ConstraintLayout>

运行效果

【线程】Android通过多线程在页面实时呈现(更新)内容_第1张图片

你可能感兴趣的:(移动端开发,android)