Android中定时器Timer和TimerTask的启动,停止,暂停,继续等操作 java timertask 停止

下面是一个在Android中使用定时器Timer和TimerTask的启动,停止,暂停,继续等操作的demo。

需要注意的问题主要有两点:

1、Timer和TimerTask在调用cancel()取消后不能再执行 schedule语句,否则提示出错,提示如下:

[java] viewplaincopyprint?
  1. D/AndroidRuntime(6672):ShuttingdownVM
  2. W/dalvikvm(6672):threadid=1:threadexitingwithuncaughtexception(group=0x40018560)
  3. E/AndroidRuntime(6672):FATALEXCEPTION:main
  4. E/AndroidRuntime(6672):java.lang.IllegalStateException:Timerwascanceled
  5. E/AndroidRuntime(6672):atjava.util.Timer.scheduleImpl(Timer.java:563)
  6. E/AndroidRuntime(6672):atjava.util.Timer.schedule(Timer.java:483)
  7. E/AndroidRuntime(6672):atcom.snowdream.timerdemo.TimerDemoActivity$2.onClick(TimerDemoActivity.java:73)
  8. E/AndroidRuntime(6672):atandroid.view.View.performClick(View.java:2501)
  9. E/AndroidRuntime(6672):atandroid.view.View$PerformClick.run(View.java:9107)
  10. E/AndroidRuntime(6672):atandroid.os.Handler.handleCallback(Handler.java:587)
  11. E/AndroidRuntime(6672):atandroid.os.Handler.dispatchMessage(Handler.java:92)
  12. E/AndroidRuntime(6672):atandroid.os.Looper.loop(Looper.java:130)
  13. E/AndroidRuntime(6672):atandroid.app.ActivityThread.main(ActivityThread.java:3835)
  14. E/AndroidRuntime(6672):atjava.lang.reflect.Method.invokeNative(NativeMethod)
  15. E/AndroidRuntime(6672):atjava.lang.reflect.Method.invoke(Method.java:507)
  16. E/AndroidRuntime(6672):atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
  17. E/AndroidRuntime(6672):atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
  18. E/AndroidRuntime(6672):atdalvik.system.NativeStart.main(NativeMethod)
  19. W/ActivityManager(154):Forcefinishingactivitycom.snowdream.timerdemo/.TimerDemoActivity
  20. W/ActivityManager(154):ActivitypausetimeoutforHistoryRecord{40550560com.snowdream.timerdemo/.TimerDemoActivity}
  21. W/ActivityManager(154):ActivitydestroytimeoutforHistoryRecord{40550560com.snowdream.timerdemo/.TimerDemoActivity}
  22. D/dalvikvm(800):GC_EXPLICITfreed13K,58%free3127K/7431K,external0K/0K,paused70ms
  23. D/dalvikvm(562):GC_EXPLICITfreed59K,51%free2935K/5959K,external245K/512K,paused84ms
  24. I/ActivityManager(154):Startproccom.android.emailforservicecom.android.email/.service.MailService:pid=6691uid=10019gids={3003,1015}
D/AndroidRuntime( 6672): Shutting down VMW/dalvikvm( 6672): threadid=1: thread exiting with uncaught exception (group=0x40018560)E/AndroidRuntime( 6672): FATAL EXCEPTION: mainE/AndroidRuntime( 6672): java.lang.IllegalStateException: Timer was canceledE/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/.TimerDemoActivityW/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 70msD/dalvikvm(  562): GC_EXPLICIT freed 59K, 51% free 2935K/5959K, external 245K/512K, paused 84msI/ActivityManager(  154): Start proc com.android.email for service com.android.email/.service.MailService: pid=6691 uid=10019 gids={3003, 1015}

2、只能在UI主线程中更新控件/组件。在其他线程中,更新控件/组件,会提示出错,提示如下:

(注:这种情况下,可以通过Hander发送消息的方式来更新控件/组件,详情参考例子。)

[java] viewplaincopyprint?
  1. E/AndroidRuntime(6309):android.view.ViewRoot$CalledFromWrongThreadException:Onlytheoriginalthreadthatcreatedaviewhierarchycantouchitsviews.
  2. E/AndroidRuntime(6309):atandroid.view.ViewRoot.checkThread(ViewRoot.java:2941)
  3. E/AndroidRuntime(6309):atandroid.view.ViewRoot.invalidateChild(ViewRoot.java:643)
  4. E/AndroidRuntime(6309):atandroid.view.ViewRoot.invalidateChildInParent(ViewRoot.java:669)
  5. E/AndroidRuntime(6309):atandroid.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
  6. E/AndroidRuntime(6309):atandroid.view.View.invalidate(View.java:5296)
  7. E/AndroidRuntime(6309):atandroid.widget.TextView.checkForRelayout(TextView.java:5533)
  8. E/AndroidRuntime(6309):atandroid.widget.TextView.setText(TextView.java:2730)
  9. E/AndroidRuntime(6309):atandroid.widget.TextView.setText(TextView.java:2598)
  10. E/AndroidRuntime(6309):atandroid.widget.TextView.setText(TextView.java:2573)
  11. E/AndroidRuntime(6309):atcom.snowdream.timerdemo.TimerDemoActivity$1.run(TimerDemoActivity.java:48)
  12. E/AndroidRuntime(6309):atjava.util.Timer$TimerImpl.run(Timer.java:284)
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

[java] viewplaincopyprint?
  1. packagecom.snowdream.timerdemo;
  2. importjava.util.Timer;
  3. importjava.util.TimerTask;
  4. importandroid.app.Activity;
  5. importandroid.os.Bundle;
  6. importandroid.os.Handler;
  7. importandroid.os.Message;
  8. importandroid.util.Log;
  9. importandroid.view.View;
  10. importandroid.widget.Button;
  11. importandroid.widget.TextView;
  12. publicclassTimerDemoActivityextendsActivity{
  13. privatestaticStringTAG="TimerDemo";
  14. privateTextViewmTextView=null;
  15. privateButtonmButton_start=null;
  16. privateButtonmButton_pause=null;
  17. privateTimermTimer=null;
  18. privateTimerTaskmTimerTask=null;
  19. privateHandlermHandler=null;
  20. privatestaticintcount=0;
  21. privatebooleanisPause=false;
  22. privatebooleanisStop=true;
  23. privatestaticintdelay=1000;//1s
  24. privatestaticintperiod=1000;//1s
  25. privatestaticfinalintUPDATE_TEXTVIEW=0;
  26. @Override
  27. publicvoidonCreate(BundlesavedInstanceState){
  28. super.onCreate(savedInstanceState);
  29. setContentView(R.layout.main);
  30. mTextView=(TextView)findViewById(R.id.mytextview);
  31. mButton_start=(Button)findViewById(R.id.mybutton_start);
  32. mButton_pause=(Button)findViewById(R.id.mybutton_pause);
  33. mButton_start.setOnClickListener(newButton.OnClickListener(){
  34. publicvoidonClick(Viewv){
  35. if(isStop){
  36. Log.i(TAG,"Start");
  37. }else{
  38. Log.i(TAG,"Stop");
  39. }
  40. isStop=!isStop;
  41. if(!isStop){
  42. startTimer();
  43. }else{
  44. stopTimer();
  45. }
  46. if(isStop){
  47. mButton_start.setText(R.string.start);
  48. }else{
  49. mButton_start.setText(R.string.stop);
  50. }
  51. }
  52. });
  53. mButton_pause.setOnClickListener(newButton.OnClickListener(){
  54. publicvoidonClick(Viewv){
  55. if(isPause){
  56. Log.i(TAG,"Resume");
  57. }else{
  58. Log.i(TAG,"Pause");
  59. }
  60. isPause=!isPause;
  61. if(isPause){
  62. mButton_pause.setText(R.string.resume);
  63. }else{
  64. mButton_pause.setText(R.string.pause);
  65. }
  66. }
  67. });
  68. mHandler=newHandler(){
  69. @Override
  70. publicvoidhandleMessage(Messagemsg){
  71. switch(msg.what){
  72. caseUPDATE_TEXTVIEW:
  73. updateTextView();
  74. break;
  75. default:
  76. break;
  77. }
  78. }
  79. };
  80. }
  81. privatevoidupdateTextView(){
  82. mTextView.setText(String.valueOf(count));
  83. }
  84. privatevoidstartTimer(){
  85. if(mTimer==null){
  86. mTimer=newTimer();
  87. }
  88. if(mTimerTask==null){
  89. mTimerTask=newTimerTask(){
  90. @Override
  91. publicvoidrun(){
  92. Log.i(TAG,"count:"+String.valueOf(count));
  93. sendMessage(UPDATE_TEXTVIEW);
  94. do{
  95. try{
  96. Log.i(TAG,"sleep(1000)...");
  97. Thread.sleep(1000);
  98. }catch(InterruptedExceptione){
  99. }
  100. }while(isPause);
  101. count++;
  102. }
  103. };
  104. }
  105. if(mTimer!=null&&mTimerTask!=null)
  106. mTimer.schedule(mTimerTask,delay,period);
  107. }
  108. privatevoidstopTimer(){
  109. if(mTimer!=null){
  110. mTimer.cancel();
  111. mTimer=null;
  112. }
  113. if(mTimerTask!=null){
  114. mTimerTask.cancel();
  115. mTimerTask=null;
  116. }
  117. count=0;
  118. }
  119. publicvoidsendMessage(intid){
  120. if(mHandler!=null){
  121. Messagemessage=Message.obtain(mHandler,id);
  122. mHandler.sendMessage(message);
  123. }
  124. }
  125. }
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[html] viewplaincopyprint?
  

爱华网本文地址 » http://www.aihuau.com/a/25101018/375983.html

更多阅读

高燃和他的女友,贵人,伙伴,公司 高燃老婆

近日,google收购了youtube,令国内视频分享网站行情日趋火爆,但下面这则消息却让人提不起精神。今日,某国内视频网站消息灵通人事透漏,MYSEE的创始人高燃被投资人挤出了管理层,作为80后的创业者,过早获得了资本的青睐,而现在又遭到了资本的驱

android中任务、进程和线程的区别 任务 进程 线程

任务、进程和线程关于Android中的组件和应用,之前涉及,大都是静态的概念。而当一个应用运行起来,就难免会需要关心进程、线程这样的概念。在Android中,组件的动态运行,有一个最与众不同的概念,就是Task,翻译成任务,应该还是比较顺理成章的。

声明:《Android中定时器Timer和TimerTask的启动,停止,暂停,继续等操作 java timertask 停止》为网友旧伤逼我嚣张分享!如侵犯到您的合法权益请联系我们删除