Android中定时器Timer和TimerTask的启动,停止,暂停,继续等操作实例
(2012-10-23 20:31:24)
标签:
定时器utf-8控件组件提示it |
下面是一个在Android中使用定时器Timer和TimerTask的启动,停止,暂停,继续等操作的demo。
需要注意的问题主要有两点:
1、Timer和TimerTask在调用cancel()取消后不能再执行 schedule语句,否则提示出错,提示如下:
-
D/AndroidRuntime(
6672): Shutting down VM - W/dalvikvm(
6672): threadid= 1:thread 0x40018560)exiting with uncaught exception (group= -
E/AndroidRuntime(
6672): FATAL EXCEPTION: main - E/AndroidRuntime(
6672): java.lang.IllegalStateException: Timer was canceled -
E/AndroidRuntime(
6672): 563)at java.util.Timer.scheduleImpl(Timer.java: - E/AndroidRuntime(
6672): 483)at java.util.Timer.schedule(Timer.java: -
E/AndroidRuntime(
6672): 2.onClick(TimerDemoActivity.java:73)at com.snowdream.timerdemo.TimerDemoActivity$ - E/AndroidRuntime(
6672): 2501)at android.view.View.performClick(View.java: -
E/AndroidRuntime(
6672): 9107)at android.view.View$PerformClick.run(View.java: - E/AndroidRuntime(
6672): 587)at android.os.Handler.handleCallback(Handler.java: -
E/AndroidRuntime(
6672): 92)at android.os.Handler.dispatchMessage(Handler.java: - E/AndroidRuntime(
6672): 130)at android.os.Looper.loop(Looper.java: -
E/AndroidRuntime(
6672): 3835)at android.app.ActivityThread.main(ActivityThread.java: - E/AndroidRuntime(
6672): at java.lang.reflect.Method.invokeNative(Native Method) -
E/AndroidRuntime(
6672): 507)at java.lang.reflect.Method.invoke(Method.java: - E/AndroidRuntime(
6672): 841)at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: -
E/AndroidRuntime(
6672): 599)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: - E/AndroidRuntime(
6672): at dalvik.system.NativeStart.main(Native Method) -
W/ActivityManager(
154):Force finishing activity com.snowdream.timerdemo/.TimerDemoActivity -
W/ActivityManager(
154):Activity forpause timeout HistoryRecord{ 40550560com.snowdream.timerdemo/.TimerDemoActivity} -
W/ActivityManager(
154):Activity fordestroy timeout HistoryRecord{ 40550560com.snowdream.timerdemo/.TimerDemoActivity} -
D/dalvikvm(
800):GC_EXPLICIT 58%freed 13K, free 3127K/7431K, external 0K/0K, paused 70ms -
D/dalvikvm(
562):GC_EXPLICIT 51%freed 59K, free 2935K/5959K, external 245K/512K, paused 84ms -
I/ActivityManager(
154):Start forproc com.android.email service 6691com.android.email/.service.MailService: pid= uid= 10019gids={ 3003,1015}
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}
2、只能在UI主线程中更新控件/组件。在其他线程中,更新控件/组件,会提示出错,提示如下:
(注:这种情况下,可以通过Hander发送消息的方式来更新控件/组件,详情参考例子。)
-
E/AndroidRuntime(
6309): android.view.ViewRoot$CalledFromWrongThreadExc eption: Only the original thread that created a view hierarchy can touch its views. - E/AndroidRuntime(
6309): 2941)at android.view.ViewRoot.checkThread(ViewRoot.java: -
E/AndroidRuntime(
6309): 643)at android.view.ViewRoot.invalidateChild(ViewRoot.java: - E/AndroidRuntime(
6309): 669)at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java: -
E/AndroidRuntime(
6309): 2511)at android.view.ViewGroup.invalidateChild(ViewGroup.java: - E/AndroidRuntime(
6309): 5296)at android.view.View.invalidate(View.java: -
E/AndroidRuntime(
6309): 5533)at android.widget.TextView.checkForRelayout(TextView.java: - E/AndroidRuntime(
6309): 2730)at android.widget.TextView.setText(TextView.java: -
E/AndroidRuntime(
6309): 2598)at android.widget.TextView.setText(TextView.java: - E/AndroidRuntime(
6309): 2573)at android.widget.TextView.setText(TextView.java: -
E/AndroidRuntime(
6309): 1.run(TimerDemoActivity.java:48)at com.snowdream.timerdemo.TimerDemoActivity$ - E/AndroidRuntime(
6309): 284)at java.util.Timer$TimerImpl.run(Timer.java:
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 extendsActivity { -
-
privatestatic String "TimerDemo";TAG = -
-
privateTextView null;mTextView = -
privateButton null;mButton_start = -
privateButton null;mButton_pause = -
-
privateTimer null;mTimer = -
privateTimerTask null;mTimerTask = -
-
privateHandler null;mHandler = -
-
privatestatic int count 0;= -
privateboolean isPause false;= -
privateboolean isStop true;= -
-
privatestatic int delay 1000;= //1s -
privatestatic int period 1000;= //1s -
-
privatestatic final int UPDATE_TEXTVIEW 0;= -
-
@Override -
publicvoid 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); -
-
-
newmButton_start.setOnClickListener( Button.OnClickListener() { -
publicvoid onClick(View v) { -
if(isStop) { -
"Start");Log.i(TAG, -
else} { -
"Stop");Log.i(TAG, -
} -
-
isStop = !isStop; -
-
if(!isStop) { -
startTimer(); -
else} { -
stopTimer(); -
} -
-
if(isStop) { -
mButton_start.setText(R.string.start); -
else} { -
mButton_start.setText(R.string.stop); -
} -
} -
}); -
-
newmButton_pause.setOnClickListener( Button.OnClickListener() { -
publicvoid onClick(View v) { -
if(isPause) { -
"Resume");Log.i(TAG, -
else} { -
"Pause");Log.i(TAG, -
} -
-
isPause = !isPause; -
-
if(isPause) { -
mButton_pause.setText(R.string.resume); -
else} { -
mButton_pause.setText(R.string.pause); -
} -
} -
}); -
-
newmHandler = Handler(){ -
-
@Override -
publicvoid handleMessage(Message msg) { -
switch(msg.what) { -
caseUPDATE_TEXTVIEW: -
updateTextView(); -
break; -
default: -
break; -
} -
} -
}; -
} -
-
privatevoid updateTextView(){ -
mTextView.setText(String.valueOf(count)); -
} -
-
privatevoid startTimer(){ -
if(mTimer null)== { -
newmTimer = Timer(); -
} -
-
if(mTimerTask null)== { -
newmTimerTask = TimerTask() { -
@Override -
publicvoid run() { -
"count:Log.i(TAG, " +String.valueOf(count)); -
sendMessage(UPDATE_TEXTVIEW); -
-
do{ -
try{ -
"sleep(1000)...");Log.i(TAG, -
1000);Thread.sleep( -
catch} (InterruptedException e) { -
} -
while} (isPause); -
-
count ++; -
} -
}; -
} -
-
if(mTimer!= null&& nullmTimerTask != ) -
mTimer.schedule(mTimerTask, delay, period); -
-
} -
-
privatevoid stopTimer(){ -
-
if(mTimer null)!= { -
mTimer.cancel(); -
null;mTimer = -
} -
-
if(mTimerTask null)!= { -
mTimerTask.cancel(); -
null;mTimerTask = -
} -
-
0;count = -
-
} -
-
publicvoid sendMessage( intid){ -
if(mHandler null)!= { -
Message message = Message.obtain(mHandler, id); -
mHandler.sendMessage(message); -
} -
} - }
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

加载中…