源码下载:

https://download.csdn.net/download/qq_31939617/10380793 下载

下面是一个在Android中使用定时器Timer和TimerTask的启动,停止,暂停,继续等操作的demo。
需要注意的问题主要有两点:
1、Timer和TimerTask在调用cancel()取消后不能再执行 schedule语句
2、只能在UI主线程中更新控件/组件。在其他线程中,更新控件/组件

MainActivity.class

package com.example.sz.timer;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.util.Timer;import java.util.TimerTask;public class MainActivity extends AppCompatActivity {    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 = 1;  //1s    private static int period = 1;  //1s    private static final int UPDATE_TEXTVIEW = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_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, "开始");                } else {                    Log.i(TAG, "停止");                }                isStop = !isStop;                if (!isStop) {                    startTimer();                }else {                    stopTimer();                }                if (isStop) {                    mButton_start.setText("开始");                } else {                    mButton_start.setText("停止");                }            }        });        mButton_pause.setOnClickListener(new Button.OnClickListener() {            public void onClick(View v) {                if (isPause) {                    Log.i(TAG, "继续");                } else {                    Log.i(TAG, "暂停");                }                isPause = !isPause;                if (isPause) {                    mButton_pause.setText("继续");                } else {                    mButton_pause.setText("暂停");                }            }        });        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);        }    }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical">    <TextView        android:id="@+id/mytextview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:text="0" />    <Button        android:id="@+id/mybutton_start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:text="开始" />    <Button        android:id="@+id/mybutton_pause"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:text="暂停" />LinearLayout>

源码下载:

https://download.csdn.net/download/qq_31939617/10380793 下载

更多相关文章

  1. Android常用控件以及用法
  2. Android中Activity界面展示与跳转及数据传递
  3. Android入门第十一篇之TabHost,TabWidget
  4. 吊打面试官:Android中高级面试题 -- 终局之战
  5. Android用户界面 UI组件--AdapterView及其子类(一) ListView及各
  6. Android之桌面组件AppWidget
  7. Android通过xml给控件添加边框
  8. Delphi XE5 for Android(安卓)(五)
  9. Kotlin初体验(一)-引入Android(安卓)Studio

随机推荐

  1. 企业分布式微服务云SpringCloud SpringBo
  2. 初用idea建立javaweb遇到的问题与心得
  3. Java递归实现算24
  4. 如何在Javascript中解析URL查询参数?(复
  5. JAVA 实现tail -f 日志文件监控功能
  6. Servlet也是一个Java类.为什么我不可以将
  7. 单例模式中的懒汉模式和饿汉模式
  8. tomcat启动web项目时候突然卡住
  9. 导致org.hibernate创建记录。MappingExce
  10. php RSA加密 JAVA 证书生成