Android定时器Timer的停止和重启实现代码
public class MainActivity extends AppCompatActivity {
private static String TAG = "TimerDemo";
private TextView mTextView = null;
private Button mButton_start = null;
private Button mButton_pause = null;
private Timer mTimer = null;
private TimerTask mTimerTask = null;
private Handler mHandler = null;
private static int count = 0;
private boolean isPause = false;
private boolean isStop = true;
private static int delay = 1000; //1s
private static int period = 1000; //1s
private static final int UPDATE_TEXTVIEW = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView)findViewById(R.id.mytextview);
mButton_start = (Button)findViewById(R.id.mybutton_start);
mButton_pause = (Button)findViewById(R.id.mybutton_pause);
mButton_start.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if (isStop) {
Log.i(TAG, "Start");
} else {
Log.i(TAG, "Stop");
}
isStop = !isStop;
if (!isStop) {
startTimer();
}else {
stopTimer();
}
if (isStop) {
mButton_start.setText(R.string.start);
} else {
mButton_start.setText(R.string.stop);
}
}
});
mButton_pause.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if (isPause) {
Log.i(TAG, "Resume");
} else {
Log.i(TAG, "Pause");
}
isPause = !isPause;
if (isPause) {
mButton_pause.setText(R.string.resume);
} else {
mButton_pause.setText(R.string.pause);
}
}
});
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_TEXTVIEW:
updateTextView();
break;
default:
break;
}
}
};
}
private void updateTextView(){
mTextView.setText(String.valueOf(count));
}
private void startTimer(){
if (mTimer == null) {
mTimer = new Timer();
}
if (mTimerTask == null) {
mTimerTask = new TimerTask() {
@Override
public void run() {
Log.i(TAG, "count: "+String.valueOf(count));
sendMessage(UPDATE_TEXTVIEW);
do {
try {
Log.i(TAG, "sleep(1000)...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} while (isPause);
count ++;
}
};
}
if(mTimer != null && mTimerTask != null )
mTimer.schedule(mTimerTask, delay, period);
}
private void stopTimer(){
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
if (mTimerTask != null) {
mTimerTask.cancel();
mTimerTask = null;
}
count = 0;
}
public void sendMessage(int id){
if (mHandler != null) {
Message message = Message.obtain(mHandler, id);
mHandler.sendMessage(message);
}
}
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播