Android应用开发中常常会用到定时器,不可避免的需要用到 TimerTask 定时器任务这个类
下面简单的一个示例演示了如何使用TimerTask

这个示例演示了3秒未有触屏事件发生则锁屏(只是设置下文本,意思一下)有触屏事件则解除锁定

public class ColTimerTaskActivity extends Activity {
/** Called when the activity is first created. */ private final String TAG = "ColTimerTaskActivity";
private final int EVENT_LOCK_WINDOW = 0x100; private TextView textView;
private Handler mHandler;
private Timer mTimer;
private MyTimerTask mTimerTask; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textview); mHandler = new Handler(){
public void handleMessage(Message message){
Log.i(TAG, "message what = " + message.what);
if (message.what == 0x100){
lockWindow();
} }
}; mTimer = new Timer(true); resumeWindow(); StartLockWindowTimer();
} public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
resumeWindow();
StartLockWindowTimer(); return super.onTouchEvent(event);
} public void resumeWindow(){
textView.setText("main window"); } public void lockWindow(){
textView.setText("lock window");
} public void StartLockWindowTimer(){
if (mTimer != null){
if (mTimerTask != null){
mTimerTask.cancel(); //将原任务从队列中移除
} mTimerTask = new MyTimerTask(); // 新建一个任务
mTimer.schedule(mTimerTask, );
}
} class MyTimerTask extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
Log.i(TAG, "run...");
Message msg = mHandler.obtainMessage(EVENT_LOCK_WINDOW);
msg.sendToTarget();
} }
}

这里需要注意两个问题:

  if (mTimerTask != null){
mTimerTask.cancel(); //将原任务从队列中移除
}

每次放定时任务前,确保之前任务已从定时器队列中移除

 mTimerTask = new MyTimerTask();  // 新建一个任务     

每次放任务都要新建一个对象,否则出现一下错误:

ERROR/AndroidRuntime(): Java.lang.IllegalStateException: TimerTask is scheduled already

所以同一个定时器任务只能被放置一次

 
 

android TimerTask 的简单应用,以及java.lang.IllegalStateException: TimerTask is scheduled already错误的解决方法【转】的更多相关文章

  1. 错误:java.lang.IllegalStateException: TimerTask is scheduled already

    Process: com.multak.cookaraclient, PID: 27384 java.lang.RuntimeException: Unable to resume activity ...

  2. java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver 错误的解决办法

    java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver 错误的解决办法 (2011-05-05 16:08:05) 转载▼ ...

  3. Spring Scheduled定时任务报错 java.lang.IllegalStateException: Encountered invalid @Scheduled method 'xxx': For input string: "2S"

    报错信息如下: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ding ...

  4. java.lang.IllegalStateException: Failed to load ApplicationContext selenium 异常 解决

    WARN <init>, HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF R ...

  5. 修改Android 4.2.2的原生Camera引出的java.lang.UnsatisfiedLinkError: Native method not found,及解决方法

    修改Android 4.2.2的原生Camera应用,做一些定制,将Camera的包名从之前的 package com.android.* 修改成了com.zhao3546.*. 调整后,应用可以正常 ...

  6. Android 用webService产生java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive错误的解决(转)

    在做android  Webservice开发的时候一般情况下大家接受webservice服务器返回值的时候都是使用 SoapObject soapObject = (SoapObject) enve ...

  7. java.lang.NoClassDefFoundError: com/gexin/rp/sdk/exceptions/RequestException解决方法

    本文为博主原创,未经允许不得转载: 最近在开发个推的时候遇到的问题,当我在maven仓库中下载个推的jar包时,下载不下来,索性在项目中Configue build Path,将jar下载到本地 手动 ...

  8. 执行Hive时出现org.apache.hadoop.util.RunJar.main(RunJar.java:136) Caused by: java.lang.NumberFormatException: For input string: "1s"错误的解决办法(图文详解)

    不多说,直接上干货 问题详情 [kfk@bigdata-pro01 apache-hive--bin]$ bin/hive Logging initialized -bin/conf/hive-log ...

  9. 关于java.lang.Exception:No tests found matching的一系列解决方法

    问题描述: java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=yahaa], {ExactMatcher ...

随机推荐

  1. python str + int

    TypeError: cannot concatenate 'str' and 'int' objects 1. print 'Is your secret number " + str(p ...

  2. linux自动备份文件和数据库并上传到指定的远程FTP中

    直接把以下脚本复制到/root/backup.sh[root@lvtao.net ~]# chmod +x /root/backup.sh[root@lvtao.net ~]# crontab -e0 ...

  3. PHPCMS收集标签使用

    调用子栏目(在栏目首页模板需要用到) {pc:content action="category" catid="$catid" num="25&quo ...

  4. 《C和指针》章节后编程练习解答参考——6.2

    <C和指针>——6.2 题目: 编写一个函数,删除源字符串中含有的子字符串部分. 函数原型: int del_substr(char *str, char const *substr); ...

  5. Tomcat8 配置Oracle11g数据源

    1:context.xml <Resource name="jdbcoracle" auth="Container" type="javax.s ...

  6. Dp解决数组中连续子数组的最大和

    #include<iostream> ];     ;i<size;i++)     {           TempSum = CurSum;           )        ...

  7. MySql的大小写问题

    原来Linux下的MySQL默认是区分表名大小写的,通过如下设置,可以让MySQL不区分表名大小写:1.用root登录,修改 /etc/my.cnf:2.在[mysqld]节点下,加入一行: lowe ...

  8. java学习面向对象构造函数

    在java当中目前我们学到的一个比较特殊的函数就是main函数,他是JVM执行的入口,所以书写的格式是固定的,现在我们来介绍java中另一个比较特殊的函数: 构造函数:构造对象的时候调用的函数,作用, ...

  9. code_analyzer(代码分析助手)

    软件名: code_analyzer 使用c语言 pcre正则库分析源码文件,包括文件中的头文件.宏定义.函数. 用途: 无聊时,可以用来打发下时间. 演示: 对于本源程序的分析结果如下: ##### ...

  10. unicode编码、字符的转换和得到汉字的区位码

    一:unicode编码.字符的转换截图 二:unicode编码.字符的转换代码 using System; using System.Collections.Generic; using System ...