欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android定时器Timer的停止和重启实现代码

程序员文章站 2023-11-27 14:44:34
本文介绍了android定时器timer的停止和重启实现代码,分享给大家,具体如下: 7月份做了一个项目,利用自定义控件呈现一幅动画,当时使用定时器来控制时间,但是当...

本文介绍了android定时器timer的停止和重启实现代码,分享给大家,具体如下:

7月份做了一个项目,利用自定义控件呈现一幅动画,当时使用定时器来控制时间,但是当停止开启时总是出现问题。一直在寻找合理的方法解决这个问题,一直没有找到,最近终于找到了合理的方法来解决这个问题。

大家如何查询有关资料,一定知道timer,timertask取消的方式是采用timer.cancel()和mtimertask.cancel(),可是大家发现这种发式取消后,再次开始timer时,会报错

 fatal exception: main
         process: com.example.zhongzhi.gate_control_scheme, pid: 2472
         java.lang.illegalstateexception: timer already cancelled.
           at java.util.timer.sched(timer.java:397)
           at java.util.timer.schedule(timer.java:248)
           at com.example.zhongzhi.gate_control_scheme.mainactivity.onclick(mainactivity.java:401)
           at android.view.view.performclick(view.java:5637)
           at android.view.view$performclick.run(view.java:22429)
           at android.os.handler.handlecallback(handler.java:751)
           at android.os.handler.dispatchmessage(handler.java:95)
           at android.os.looper.loop(looper.java:154)
           at android.app.activitythread.main(activitythread.java:6119)
           at java.lang.reflect.method.invoke(native method)
           at com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:886)
           at com.android.internal.os.zygoteinit.main(zygoteinit.java:776)

 这个问题的解决采用cancle(),取消timer后,还需要清空timer。合理的代码应该是这样的:

mtimer.cancel();
mtimer = null;
mtimertask.cancel();
mtimertask = null;

关键的问题解决完了,下面给出我的案例代码mainactivity.java:

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);
    }
  }
}

xml部分代码:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <textview
    android:id="@+id/mytextview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/number" />

  <linearlayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal" >

    <button
      android:id="@+id/mybutton_start"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/start" />

    <button
      android:id="@+id/mybutton_pause"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/pause" />
  </linearlayout>
</linearlayout>

string部分代码:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">timerdemo</string>
  <string name="number">0</string>
  <string name="start">start</string>
  <string name="stop">stop</string>
  <string name="pause">pause</string>
  <string name="resume">resume</string>
</resources>

上面就是我的源代码,如果大家有什么问题可以留言进行探讨。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。