文章目录
一、倒计时器功能描述
这里我们通过倒计时器的案例来讲解Android多线程编程。
其中:
(1)子线程用于计时,一秒钟向主线程发送一次消息。
(2)主线程用于接收消息并更新UI控件——TEXTVIEW
二、实现步骤
1.新建Activity,命名为ThreadDemo
2.设计ThreadDemo 的布局文件
<?xml version="1.0" encoding="utf-8"?>
<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=".ThreadDemo">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginTop="100dp"
android:text="TextView"
android:textColor="@color/colorAccent"
android:textSize="32sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:text="开始倒计时"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
3.编写ThreadDemo.java 文件代码
3.1 定义全局变量
下面展示一些 内联代码片
,注意全局变量放置位置
private final int UPDATE_TEXT =0x03;
private final int UPDATE_TIME =0x04;
boolean isStop = false;
private int number =6;
3.2 定义子线程,发送消息
子线程在Thread Demo类中定义,代码如下:
实例化一个子线程,命名为th02;
final Thread th02 = new Thread(new Runnable() {
@Override
public void run() {
while(!isStop){
try{
Thread.sleep(1000);
Message msg = Message.obtain();
msg.what = UPDATE_TIME;
//msg.arg1 = NUM+1;
myHandle.sendMessage(msg);
Log.i("ThreadDemo","ThreadRun");
}
catch (Exception e){
Log.e("Error",e.toString());
}
}
}
});
其中用到了myHandle实例,myHandle实例的定义在3.3小节中,此处敲击代码时报错请忽略。
3.3 定义Handler,接收消息
实例化Handler,命名为myHandle,接收消息,并更新UI
Handler myHandle =new Handler(){
@Override
public void handleMessage(@Nullable Message msg){
TextView tv =findViewById(R.id.textView3);
switch(msg.what){
case UPDATE_TEXT:
tv.setText("已经更新了。");
break;
case UPDATE_TIME:
if(number==0){
isStop = true;
tv.setText("时间到!");
break;
}
number = number -1;
tv.setText(Integer.toString(number));
Log.i("ThreadDemo",Integer.toString(number));
Log.i("ThreadDemo",th02.getState().toString());
break;
//tv.setText("UPDATE_TIME");
}
}
};
3.4 定义按钮点击事件,添加监听器
当点击按钮时,开启th02
findViewById(R.id.btStart).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isStop = false;
Log.i("ThreadDemo",th02.getState().toString());
th02.start();
}
});
总结
以上就是今天要讲的内容,本文仅仅简单介绍了计时器的实例的实现步骤,体会代码中Log.i()对调试程序的作用。大家在此基础上可以完善程序功能,如倒计时的初始时间可以自己设定
思考:
倒计时结束后,如何重启倒计时器?