package com.example.timertiaozhuandemo;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private Button button;
//Looper
int miao = 5;
// 1.
Timer timer = new Timer();
// 2.
TimerTask task = new TimerTask() {
@Override
public void run() {
/**
* 放在主线程去执行任务
*/
runOnUiThread(new Runnable() {
public void run() {
if (miao > 0) {
miao --;
textView.setText(miao+"秒后跳转");
}else {
//4.
timer.cancel();
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
// 3.
timer.schedule(task, 1000, 1000);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
timer.cancel();
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
});
}
}