赞
踩
在Android中,用到timer时,代码:
- private int second_counts;
- private Timer timer;//定时器
- private TimerTask timerTask;
- private Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- try {
- int count = (int )msg.obj;
- showTimeBar(count);
- }catch (Exception e){
- showTimeBar(0);
- }
- }
- };
- private void showTimeBar(int seconds){
- if (seconds<=0){
- destroyTimer();
- Log.e("tag_fly","over");
- return;
- }
- Log.e("Tag_fly","second:"+seconds);
- }
初始化:
- private void initTimer()
- {
- if (timer == null){
- timer = new Timer();
- }
- if (timerTask==null){
- timerTask = new TimerTask() {
- @Override
- public void run() {
- Message m = new Message();
- m.obj = second_counts;
- handler.sendMessage(m);
- second_counts--;
- }
- };
- }
- }
销毁:
- private void destroyTimer() {
- if (timer != null) {
- timer.cancel();
- timer = null;
- }
- if (timerTask != null) {
- timerTask.cancel();
- timerTask = null;
- }
- }
引入包名:
- import android.os.Handler;
- import android.os.Message;
- import java.util.Timer;
- import java.util.TimerTask;
调用:
- second_counts = 100;
- initTimer();
- timer.schedule(timerTask,0,1000);
回收:
- @Override
- protected void onStop() {
- super.onStop();
- destroyTimer();
- }
-
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- destroyTimer();
- }
返回到当前控制器(activity):
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode){
- case RESTART_REQUESTCODE:
- if (second_counts>0){//此处判断是否调用timer
- initTimer();
- timer.schedule(timerTask,0,1000);//重新启动timer
- }
- break;
- default:
- break;
- }
- }
注释:
调用其它界面,使用函数:
startActivityForResult(intent, RESTART_REQUESTCODE);
- destroyTimer();
- second_counts = 100;
- initTimer();
- timer.schedule(timerTask,0,1000);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。