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

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

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

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

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

http://blog.csdn.net/snowdream86/article/details/7072530

 

 

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/MMLoveMeMM/articles/3617045.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值