一、 说明
只需要重写Handler类中处理消息的方法,当新启动的线程发送消息时,Handler类中处理消息的方法就会被自动回调。
二、代码
- java代码
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity
{
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=findViewById(R.id.tv);//文本框的实例化
final Handler handler=new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what==0x1233)//如果消息是本程序所发送的
{
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(date);
tv.setText(format);
}
super.handleMessage(msg);
}
};
//使用定时器,每隔1000毫秒发送一个消息
new Timer().schedule(new TimerTask()
{
@Override
public void run()
{
Message message=new Message();
message.what=0x1233;
handler.sendMessage(message);
}
},0,1000);
}
}
- 界面代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:gravity="center"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>