当前位置:   article > 正文

Timer使用_private timer

private timer

在Android中,用到timer时,代码:

  1. private int second_counts;
  2.  private Timer timer;//定时器
  3. private TimerTask timerTask;
  4. private Handler handler = new Handler() {
  5. @Override
  6. public void handleMessage(Message msg) {
  7. try {
  8. int count = (int )msg.obj;
  9. showTimeBar(count);
  10. }catch (Exception e){
  11. showTimeBar(0);
  12. }
  13. }
  14. };

  1. private void showTimeBar(int seconds){
  2. if (seconds<=0){
  3. destroyTimer();
  4. Log.e("tag_fly","over");
  5. return;
  6. }
  7. Log.e("Tag_fly","second:"+seconds);
  8. }

初始化:

  1. private void initTimer()
  2. {
  3. if (timer == null){
  4. timer = new Timer();
  5. }
  6. if (timerTask==null){
  7. timerTask = new TimerTask() {
  8. @Override
  9. public void run() {
  10. Message m = new Message();
  11. m.obj = second_counts;
  12. handler.sendMessage(m);
  13. second_counts--;
  14. }
  15. };
  16. }
  17. }

销毁:

  1. private void destroyTimer() {
  2. if (timer != null) {
  3. timer.cancel();
  4. timer = null;
  5. }
  6. if (timerTask != null) {
  7. timerTask.cancel();
  8. timerTask = null;
  9. }
  10. }
引入包名:
  1. import android.os.Handler;
  2. import android.os.Message;
  3. import java.util.Timer;
  4. import java.util.TimerTask;

调用:

  1. second_counts = 100;
  2. initTimer();
  3. timer.schedule(timerTask,0,1000);

回收:

  1. @Override
  2. protected void onStop() {
  3. super.onStop();
  4. destroyTimer();
  5. }
  6. @Override
  7. protected void onDestroy() {
  8. super.onDestroy();
  9. destroyTimer();
  10. }

返回到当前控制器(activity):

  1. @Override
  2. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  3. super.onActivityResult(requestCode, resultCode, data);
  4. switch (requestCode){
  5. case RESTART_REQUESTCODE:
  6. if (second_counts>0){//此处判断是否调用timer
  7. initTimer();
  8. timer.schedule(timerTask,0,1000);//重新启动timer
  9. }
  10. break;
  11. default:
  12. break;
  13. }
  14. }

注释:

调用其它界面,使用函数:

            startActivityForResult(intent, RESTART_REQUESTCODE);

当代码中会多次调用timer时,需要在调用前,销毁原来的timer,故此,启动timer代码可以优化为:

  1. destroyTimer();
  2. second_counts = 100;
  3. initTimer();
  4. timer.schedule(timerTask,0,1000);

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号