Android中提供了通信机制,Message、Handler 等,Message用于在子线程中传递数据,Handler用于发送数据到主线程中,
下面介绍基于Message、Handler的计时器
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TimeActivity extends AppCompatActivity {
private TextView tv; //布局中用于显示计时数字
private Button time; //布局中设置Button,用于开始计时
private int a=100;
private Handler handler =new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv.setText(srt+msg.what + "");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time);
tv= (TextView) findViewById(R.id.tv);
time= (Button) findViewById(R.id.time);
tv.setText("100");
time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new time()).start(); //调用time类
}
});
}
public class time implements Runnable{
@Override
public void run() {
int i=100;
while(i>=0){
try {
Thread.sleep(200); //延时0.5秒
} catch (InterruptedException e) {
e.printStackTrace();
}
i--;
handler.sendEmptyMessage(i); //Handler方法
}
}
}
}