Android中定時器Timer和TimerTask的啟動,停止,暫停,繼續等操作例項
需要注意的問題主要有兩點:
1、Timer和TimerTask在呼叫cancel()取消後不能再執行 schedule語句,否則提示出錯,提示如下:
2、只能在UI主執行緒中更新控制元件/元件。在其他執行緒中,更新控制元件/元件,會提示出錯,提示如下:D/AndroidRuntime( 6672): Shutting down VM W/dalvikvm( 6672): threadid=1: thread exiting with uncaught exception (group=0x40018560) E/AndroidRuntime( 6672): FATAL EXCEPTION: main E/AndroidRuntime( 6672): java.lang.IllegalStateException: Timer was canceled E/AndroidRuntime( 6672): at java.util.Timer.scheduleImpl(Timer.java:563) E/AndroidRuntime( 6672): at java.util.Timer.schedule(Timer.java:483) E/AndroidRuntime( 6672): at com.snowdream.timerdemo.TimerDemoActivity$2.onClick(TimerDemoActivity.java:73) E/AndroidRuntime( 6672): at android.view.View.performClick(View.java:2501) E/AndroidRuntime( 6672): at android.view.View$PerformClick.run(View.java:9107) E/AndroidRuntime( 6672): at android.os.Handler.handleCallback(Handler.java:587) E/AndroidRuntime( 6672): at android.os.Handler.dispatchMessage(Handler.java:92) E/AndroidRuntime( 6672): at android.os.Looper.loop(Looper.java:130) E/AndroidRuntime( 6672): at android.app.ActivityThread.main(ActivityThread.java:3835) E/AndroidRuntime( 6672): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime( 6672): at java.lang.reflect.Method.invoke(Method.java:507) E/AndroidRuntime( 6672): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) E/AndroidRuntime( 6672): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) E/AndroidRuntime( 6672): at dalvik.system.NativeStart.main(Native Method) W/ActivityManager( 154): Force finishing activity com.snowdream.timerdemo/.TimerDemoActivity W/ActivityManager( 154): Activity pause timeout for HistoryRecord{40550560 com.snowdream.timerdemo/.TimerDemoActivity} W/ActivityManager( 154): Activity destroy timeout for HistoryRecord{40550560 com.snowdream.timerdemo/.TimerDemoActivity} D/dalvikvm( 800): GC_EXPLICIT freed 13K, 58% free 3127K/7431K, external 0K/0K, paused 70ms D/dalvikvm( 562): GC_EXPLICIT freed 59K, 51% free 2935K/5959K, external 245K/512K, paused 84ms I/ActivityManager( 154): Start proc com.android.email for service com.android.email/.service.MailService: pid=6691 uid=10019 gids={3003, 1015}
(注:這種情況下,可以通過Hander傳送訊息的方式來更新控制元件/元件,詳情參考例子。)
E/AndroidRuntime( 6309): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. E/AndroidRuntime( 6309): at android.view.ViewRoot.checkThread(ViewRoot.java:2941) E/AndroidRuntime( 6309): at android.view.ViewRoot.invalidateChild(ViewRoot.java:643) E/AndroidRuntime( 6309): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:669) E/AndroidRuntime( 6309): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511) E/AndroidRuntime( 6309): at android.view.View.invalidate(View.java:5296) E/AndroidRuntime( 6309): at android.widget.TextView.checkForRelayout(TextView.java:5533) E/AndroidRuntime( 6309): at android.widget.TextView.setText(TextView.java:2730) E/AndroidRuntime( 6309): at android.widget.TextView.setText(TextView.java:2598) E/AndroidRuntime( 6309): at android.widget.TextView.setText(TextView.java:2573) E/AndroidRuntime( 6309): at com.snowdream.timerdemo.TimerDemoActivity$1.run(TimerDemoActivity.java:48) E/AndroidRuntime( 6309): at java.util.Timer$TimerImpl.run(Timer.java:284)
Demo原始碼如下: TimerDemoActivity.java
package com.snowdream.timerdemo; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class TimerDemoActivity extends Activity { 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.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); } } }
layout-main.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>
strings.xml
<?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>
原始碼下載:http://download.csdn.net/detail/yang_hui1986527/3922447
相關推薦
Android中定時器Timer和TimerTask的啟動,停止,暫停,繼續等操作例項
下面是一個在Android中使用定時器Timer和TimerTask的啟動,停止,暫停,繼續等操作的demo。 需要注意的問題主要有兩點: 1、Timer和TimerTask在呼叫cancel()取消後不能再執行 schedule語句,否則提示出錯,提示如下:D/Andro
定時器的實現、java定時器Timer和Quartz介紹與Spring中定時器的配置
欄位 允許值 允許的特殊字元 秒 0-59 , - * / 分 0-59 , - * / 小時 0-23 , - * / 日期 1-31 , - * ? / L W C 月份 1-12 或者 JAN-DEC , - * / 星期 1-7 或者 SUN-SAT , - *
emWin 2天速成實例教程004_軟件定時器(Timer)和位圖片動畫
emwin timer image 定時器 動畫 備註:(1)打開工程目錄下的"Exe\GUISimulationDebug.exe"即可看到效果。(2)看完教程000~005就基本會用emWin做項目,其他章節可以需要時再參考。 emWin的TIMER是一個軟件定時
js中定時器setTimeout和setInterval兩種定時器
專案中,經常會用到定時器來實現資料實時更新、時間等,簡單總結一下: Javascript中的定時器有兩種,setInterval和setTimeout,而定時器的作用就是延遲執行。 一、定時器的寫法 setInterval(expression,milliseconds);
android中定時器的實現學習
資料來自於 簡書 沿路旅程如歌蛻變 點這裡 利用handler.postDelay()方法來實現定時器計時 下面的程式碼實現了6s倒計時,計時後,自動停止計時並移除runnable. public class MainActivity extends AppCompat
Android開發定時器(Timer)的使用
方式1:執行單一定時器任務 Timer timer = new Timer(); timer.schedule(new TimerTask() { @Overri
Windows中定時器Timer使用中的注意事項
在任何語言任何作業系統下的開發中,定時器都是一個必不可少的功能,大部分的作業系統和語言都有內建的定時器介面可供呼叫。在windows API中有一組定時器相關函式,包括CreateTimerQueue、DeleteTimerQueue、CreateTimerQueue
Android關於定時器Timer的定義及用法
今天主要說一下關於定時器Timer的用法及應用場景 還是接著昨天關於回撥函式的例子,詳細請看我的上一篇Android關於回撥函式的定義及用法 在此基礎上定義定時器,並不斷請求資料,進行介面更新操作。這種情況一般應用在當我的介面需要不停的更新資料時。 例如,
Java Web專案中定時器Timer的使用
在以前的文章中,曾經寫過一個排程器Quartz的使用例項,今天,分享一個JDK自帶的定時器Timer在Java Web專案中的使用。 首先,簡單說一下Quartz和Timer的相同和不同之處: 相同:他們都是定時去執行一些操作,比如,定時刪除一些過期資料,定
C#中定時器Timer與DispatcherTimer的用法
最近的工作專案中需要定時更新UI控制元件中的資料,這時候第一反應肯定會想到去使用System.Timers.Timer定時更新UI控制元件,但是程式執行後,會發現程式崩潰了。報的異常為“呼叫執行緒無法訪問此物件,因為另一個執行緒擁有該物件。”,網上查找了原因,Timer的觸發事件與UI不是屬於同一個執行緒,所
.NET Framework中定時器timer的單執行緒與多執行緒使用講解
如果你需要使用規律的時間間隔重複執行一些方法,最簡單的方式是使用定時器(timer)。與下邊的例子相比,定時器可以便捷、高效地使用記憶體和資源: ? 1 2 3 4 5 6 7 new Thread (delegate() { while (enabled)
Java中定時器Timer致命缺點(附學習方法)
簡介 這篇文章我一直在糾結到底要不要寫,不想寫一來因為定時器用法比較簡單,二來是面試中也不常問。後來還是決定寫了主要是想把自己分析問題思路分享給大家,讓大家在學習過程中能夠參考,學習態度我相信大部分人沒有問題,特別是正在看我博文的小夥伴那更不用說了!!給你們點個狂力贊。接下來就是學習方法了
PHP中MongoDB資料庫的連線、新增、修改、查詢、刪除等操作例項
PHP 擴充套件mongon.mod.dll下載http://cn.php.net/manual/en/mongo.installation.php#mongo.installation.windows 然後php.ini新增 extension=php_mongo.dll
Java 中Timer和TimerTask 定時器和定時任務使用的例子
這兩個類使用起來非常方便,可以完成我們對定時器的絕大多數需求 Timer類是用來執行任務的類,它接受一個TimerTask做引數 Timer有兩種執行任務的模式,最常用的是schedule,它可以以兩種方式執行任務:1:在某個時間(Data),2:在某個固定的時間之後(i
多線程中sleep和wait的區別,以及多線程的實現方式及原因,定時器--Timer
守護 驗證 取消 技術 方法 代碼 安全 接口 art 1. Java中sleep和wait的區別 ① 這兩個方法來自不同的類分別是,sleep來自Thread類,和wait來自Object類。 sleep是Thread的靜態類方法,誰調用的誰去睡覺,即使在a線程裏調用b
Timer和TimerTask定時器使用
Timer是一種定時器工具,用來在一個後臺執行緒計劃執行指定任務。它可以計劃執行一個任務一次或反覆多次。 TimerTask一個抽象類,它的子類代表一個可以被Timer計劃的任務。具體的任務在TimerTask中run介面中實現。 通過Timer中的schedule方法啟動定
Android中使用Timer和TimerTask
前言 近期有個需求,要每隔一段時間,應用向後臺傳送一些資料,用作統計,這時可以使用Java提供的計時器的工具類,即Timer和TimerTask來實現這一功能。 簡介 Timer是一個普通的類,其中有幾個重要的方法;而TimerTask則是一個抽象類
心跳包定時器實現(Timer和TimerTask詳解)
如果要執行一些簡單的定時器任務,無須做複雜的控制,也無須儲存狀態,那麼可以考慮使用JDK 入門級的定期器Timer來執行重複任務。一、原理JDK中,定時器任務的執行需要兩個基本的類:java.util.Timer;java.util.TimerTask;要執行一個定時任務,最
Java中的Timer和TimerTask在Android中的用法
在開發中我們有時會有這樣的需求,即在固定的每隔一段時間執行某一個任務。比如UI上的控制元件需要隨著時間改變,我們可以使用Java為我們提供的計時器的工具類,即Timer和TimerTask。 Timer是一個普通的類,其中有幾個重要的方法;而TimerTask則是一個抽象
Java定時器(一)Timer和TimerTask
方式一:設定指定任務task在指定時間time執行 schedule(TimerTask task, Date date)public static void main(String[] args) t