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方法 } } }}