欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Studio 之 Android消息机制 之简单Demo --- 使用Handler和Message类来完成消息传递

程序员文章站 2022-07-14 21:50:35
...

这里也是一个简单的Timer定时器的示例。

布局文件hm_main.xml源码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.java源码如下:

package com.example.jimmy.hm_demo;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private static int nCount = 0;
    public static final int MSG_SET = 1;

    private TextView tv_show = null;

    private final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MSG_SET:
                    tv_show.setText("Timer is up, " + nCount++);
                    break;
            }
        }
    };

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

        tv_show = (TextView)findViewById(R.id.tv_show);

        Timer timer = new Timer();
        timer.schedule(new MyTask(), 1000, 1000);
    }

    private class MyTask extends TimerTask
    {
        @Override
        public void run() {
            Message msg = new Message();
            msg.what = MSG_SET;
            mHandler.sendMessage(msg);
        }
    }
}

 

---- The End.