本文介绍了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部分代码:

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

android:id="@+id/mytextview"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:text="@string/number" />

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal" >

android:id="@+id/mybutton_start"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/start" />

android:id="@+id/mybutton_pause"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/pause" />

string部分代码:

TimerDemo

0

start

stop

pause

resume

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

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

java定时器关闭再重启_Android定时器Timer的停止和重启实现代码相关推荐

  1. 解决定时器关闭不掉的问题,clearInterval无效

    1.环境问题,this.interVal是我定义的定时器 如直接写clearInterval(this.interVal);不好用,需要换成window.clearInterval(this.inte ...

  2. Linux 系统服务管理(启动服务/停止服务/重启服务)的命令 - chkconfig/service/systemctl

    文章目录 一.使用命令 chkconfig 管理系统服务 (一)命令介绍 二.使用命令 service 管理系统服务 (一)命令介绍 (二)命令用法 1.启动服务 2.停止服务 3.重启服务 4.查看 ...

  3. 服务器重启oracle数据库服务器,oracle数据库怎么重启_网站服务器运行维护,oracle,数据库,重启...

    linux操作系统好学吗_网站服务器运行维护 学习大多类似鹿丁解牛,对事物的认识一般都是由浅入深.由表及里的过程,循序才能渐进.学习Linux同样要有一定的顺序和方法,这样学起来就不会感觉到难了. o ...

  4. Java多线程学习笔记20之定时器Timer

    详细代码见:github代码地址 本节内容: 定时器Timer的使用及分析 1) 如何实现指定时间执行任务 2) 如何实现按指定周期执行任务 第五章 定时器Timer 定时/计划功能在移动开发领域使用 ...

  5. java timertask 初始化_定时器实现方式之TimerTask、Timer

    在未来某个指定的时间点或者经过一段时间延迟后执行某个事件,这时候就需要用到定时器了.定时器的实现方式有很多种,今天总结最简单的实现方式.java 1.3引入了定时器框架,用于在定时器上下文中控制线程的 ...

  6. java 定时器获得外部参数_JMeter定时器使用小结

    一.定时器的作用域 1.无论定时器位置在Sampler之前还是下面,定时器是在每个sampler(采样器)之前执行的,而不是之后: 2.当执行一个Sampler之前时,所有当前作用域内的定时器都会被执 ...

  7. 【JAVA定时器】四种常见定时器的原理和简单实现

    个人学习笔记分享,当前能力有限,请勿贬低,菜鸟互学,大佬绕道 如有勘误,欢迎指出和讨论,本文后期也会进行修正和补充 前言 定时器顾名思义,即定时触发某个事件,分离开来,即包含三个因素:定时,触发,某个 ...

  8. 定时器实现方式之TimerTask、Timer

    在未来某个指定的时间点或者经过一段时间延迟后执行某个事件,这时候就需要用到定时器了.定时器的实现方式有很多种,今天总结最简单的实现方式.java 1.3引入了定时器框架,用于在定时器上下文中控制线程的 ...

  9. java定时器 并发_【java多线程与并发库】— 定时器的应用 | 学步园

    定时器的应用 1.  定时器主要涉及到两个类(java.util包中) @->public class Timer extendsObject (一种工具,线程用其安排以后在后台线程中执行的任务 ...

最新文章

  1. BCH三小时缓慢出块——需要重视的小概率事件
  2. blp模型 上读下写_CreditX在线借贷欺诈检测框架BLP
  3. Java应用全链路启动速度提升至15s,阿里云SAE能力再升级
  4. 阿里云前端周刊 - 第 26 期
  5. mysql的concat函数_MySQL中concat函数(连接字符串)
  6. 一个拆分使用的存储过程例子
  7. mpvue 从零开始 女友的衣装 1 pages
  8. linux so文件统一目录,linux加载指定目录的so文件
  9. Python《爬虫再练手》
  10. c语言学习-判断101-200之间有多少个素数,并输出所有素数及素数的个数
  11. Tarjan算法查找强联通组件的程序
  12. java中数据类型及运算符的注意事项
  13. 【转】Java杂谈(四)
  14. Qt中QBitmap 的使用 --QBitmap的作用
  15. eslint 报error
  16. DB9引脚在UART,CAN,RS485中的定义
  17. Visual Foxpro 6.0教程
  18. window10运行不了1stopt_1stopt软件到底性能怎样?
  19. 校验子解码问题(Syndrome Decoding)
  20. 用html制作四行四列的表格,HTML表格元素

热门文章

  1. android支持苹果吗,安卓手机能用苹果USB-C音频线吗?实测10款手机仅1款不支持
  2. Conflux Studio 安装教学
  3. Arcpy 通过mxd模版生成专题图
  4. Programming Exercise 7: K-means Clustering and Principal Component Analysis【Maching Learning】
  5. 计算机b级及格线,计算机一级B考试有那些内容?理论部分不几个就算总分及格了也不算合格吗?...
  6. vivado导入tcl例程
  7. 毕业设计第一次总结(基于知识图谱的医疗问答)
  8. 【兼容性测试】21个兼容性测试需要注意的测试点
  9. python编写图形化界面的工具,python做出软件的界面
  10. css 遥控器界面,智能电视用户体验设计之遥控器篇