Android定时器实现定时执行、重复执行、定时重复执行、定次数执行的多种方式

作用:

1、定时执行某种功能

2、重复执行、定时重复执行、定次数执行某种功能

类别:

1、 Thread(new Runnable)

2、Thread()

3、Timer

4、Handler

·····

代码如下:

1、布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="match_parent"
  android:layout_height="match_parent">
  <Button
    android:id="@+id/show_time"
    android:text="请选择一种启动方式"
    android:textSize="30dp"
    android:layout_width="match_parent"
    android:layout_height="100dp" />
   <Button
     android:id="@+id/timer_1"
     android:textAllCaps="false"
     android:text="定时方式1(Thread(new Runnable))"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />
   <Button
     android:id="@+id/timer_2"
     android:text="定时方式2(Thread())             "
     android:textAllCaps="false"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />
   <Button
     android:id="@+id/timer_3"
     android:text="定时方式3(Timer)               "
     android:textAllCaps="false"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />
   <Button
     android:id="@+id/timer_4"
     android:text="定时方式4(Handler)             "
     android:textAllCaps="false"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />
    <Button
     android:id="@+id/clear"
     android:text="计时器清零                    "
     android:layout_width="match_parent"
     android:layout_height="wrap_content" />
  <TextView
    android:layout_margin="10dp"
    android:text="方式3停止方式不同(因为Timer一旦被cancel之后就废了,只有重新构造一个)\n停止:1、开启3 2、点击停止 3、再点击方式3"
    android:textAllCaps="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

2、实现定时功能

package com.example.leixiansheng.mytimers;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  private Button timer_1, timer_2, timer_3, timer_4,clear, showTime;
  private Timer timer;
  private TimerTask timerTask;
  private int num = 0;    //计数值
  private boolean flog = true;    //是否停止计时
  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      showTime.setText("点击我停止计时: " + msg.what);
    }
  };
  //handler 方式定时循环
  private Handler handlerTimer = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      if (flog) {
        handlerTimer.sendEmptyMessageDelayed(num++, 1000);
      }
      showTime.setText("点击我停止计时: " + msg.what);
      if(flog == false) {
       flog = true;
      }
    }
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer_1 = (Button) findViewById(R.id.timer_1);
    timer_2 = (Button) findViewById(R.id.timer_2);
    timer_3 = (Button) findViewById(R.id.timer_3);
    timer_4 = (Button) findViewById(R.id.timer_4);
    clear = (Button) findViewById(R.id.clear);
    showTime = (Button) findViewById(R.id.show_time);
    timer_1.setOnClickListener(this);
    timer_2.setOnClickListener(this);
    timer_3.setOnClickListener(this);
    timer_4.setOnClickListener(this);
    clear.setOnClickListener(this);
    showTime.setOnClickListener(this);
  }
  @Override
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.timer_1:
        method_1();
        break;
      case R.id.timer_2:
        method_2();
        break;
      case R.id.timer_3:
        method_3();
        break;
      case R.id.timer_4:
        method_4();
        break;
      case R.id.clear:
        num = 0;
        showTime.setText("请选择一种启动方式");
        break;
      case R.id.show_time:
        flog = false;
        break;
    }
  }
  private void method_4() {
      new Thread() {
        @Override
        public void run() {
          super.run();
          handlerTimer.sendEmptyMessage(num++);
        }
      }.start();
  }
  private void method_3() {
    //Timer一旦被cancel之后就废了,只有重新构造一个。
    if (flog == true) {
      timer = new Timer();
      timerTask = new TimerTask() {
        @Override
        public void run() {
          handler.sendEmptyMessage(num++);
        }
      };
      /**
       * 第一个参数:任务
       * 第二个参数:初始启动等待时间
       * 第三个参数:时间间隔
       */
      timer.schedule(timerTask, 0, 1000);
    } else {
      timer.cancel();
      // 一定设置为null,否则定时器不会被回收
      timer = null;
      flog = true;
    }
    //Timer 暂停重启有问题(待改进)
    //Timer一旦被cancel之后就废了,只有重新构造一个。
//    if (flog == true) {
//      timerTask = new TimerTask() {
//        @Override
//        public void run() {
//          handler.sendEmptyMessage(num++);
//        }
//      };
//      /**
//       * 第一个参数:任务
//       * 第二个参数:初始启动等待时间
//       * 第三个参数:时间间隔
//       */
//      timer.schedule(timerTask, 0, 1000);
//    } else {
//      timer.cancel();
//      flog = true;
//    }
  }
  private void method_2() {
    //new Thread().start();
    new Thread() {
      @Override
      public void run() {
        super.run();
        while (flog) {
          handler.sendEmptyMessage(num++);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }.start();
    flog = true;
  }
  private void method_1() {
//    new Thread(new Runnable).start();
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (flog) {
          handler.sendEmptyMessage(num++);
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
    flog = true;
  }
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

(0)

相关推荐

  • Android带刷新时间显示的PullToRefresh上下拉刷新

    用过很多上下拉刷新,找到一个让自己满意的确实不容易,有些好的刷新控件,也并不是公司所需要的,在这里我给大家推荐一下我所喜欢的上下拉控件,实现也挺简单,需要的不妨来用一下,效果一看便知 加载就是一个圆形进度条,一个正在加载Textview,我就不上图了 这个是刷新的头布局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.an

  • android如何取得本地通讯录的头像的原图的实现代码

    本文介绍了android如何取得本地通讯录的头像的原图的实现代码,分享给大家,也给自己留个笔记 如果想通讯录进入详情页,那么最重要的参数就是contactId,这个是联系人的唯一标识 getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position

  • Android实现外部唤起应用跳转指定页面的方法

    前言 通常有这么一个场景,就是分享内容到微信朋友圈等,然后点击内容中的某个按钮就可以唤起自家应用. 这里要讲的也是使用 scheme 的方式去实现跳转,先捋一捋思路,首先如果要外部能唤醒 App ,那么 App 肯定要先注册一个全局的事件监听吧.然后,应该有一个页面来处理接受事件然后解析出具体的参数然后跳转具体的页面.就是这么简单. 思路捋好来,那么就来一一实现吧. 注册事件监听 这里需要使用到 Android Activity中的 <intent-filter> ,现在可以创建一个解析跳转的

  • Android中buildToolVersion与CompileSdkVersion的区别

    SDK中主要的目录: [build-tools]里面是不同版本(例如21.1.1)的build工具,这些工具包括了aapt打包工具.dx.bat.aidl.exe等等 [platform]是存放不同API-level版本SDK目录的地方 [platform-tools]是一些android平台相关的工具,adb.fastboot等 [tools]是指的安卓开发相关的工具,例如android.bat.ddms.bat(Dalvik debug Monitor Service).draw9patch

  • Android仿微信标签功能

    微信中有对联系人添加标签的功能,如下图所示. 这里有三种状态的标签,分别的未选择,选中,编辑中,由于前两种标签不需要提供输入,所以用TextView实现即可,编辑中的标签用EditText来实现.而标签的形状就用Shape来实现. 在drawable下新建xml文件,这里先上Shape的xml文件. tag_normal.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android=

  • Android加载loading对话框的功能及实例代码(不退出沉浸式效果)

    一.自定义Dialog 在沉浸式效果下,当界面弹出对话框时,对话框将获取到焦点,这将导致界面退出沉浸式效果,那么是不是能通过屏蔽对话框获取焦点来达到不退出沉浸式的目的呢.说干就干,我们先来看一下改善后的效果图. 普通对话框弹出效果 LoadingDialog弹出效果 自定义LoadingDialog public class LoadingDialog extends Dialog { public LoadingDialog(Context context) { super(context);

  • Android中LayoutInflater.inflater()的正确打开方式

    前言 LayoutInflater在开发中使用频率很高,但是一直没有太知道LayoutInflater.from(context).inflate()的真正用法,今天就看看源码的流程. 首先来看from()的源码: /** * Obtains the LayoutInflater from the given context. */ public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater

  • Android单一实例全局可调用网络加载弹窗

    最近因为项目需求,需要完成一个全局的网络加载弹窗需求,真正完成这个需求之后,感觉最重要的不是结果,而是思维. 我刚开始接到这个需求的时候,第一种想到的方案是 基类加单例.但是实际做起来之后发现,因为单例的原因,你的弹窗只能在第一次创建这个单例的activity中显示出来. 那么发现这个问题之后在这个的基础上改进一下,如果我不用activity的上下文,而是采用类似于Application的一种全局上下文呢?当然,个人能力有限,这种想法就给毙掉了,后来由导师指点,利用service的上下文,dia

  • android的ListView点击item使item展开的做法的实现代码

    本文介绍了android的ListView点击item使item展开的做法的实现代码,分享给大家,具体如下: 效果图: 原理是点击item的时候,重新measure list的各个item的高度 list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { My

  • Android实现动态添加标签及其点击事件

    在做Android开发的时候,会遇到动态添加标签让用户选择的功能,所以自己写了个例子,运行效果图如下. 标签可以左右滑动进行选择,点击的时候,会弹出toast提示选择或者取消选择了哪个标签.通过动态添加TextView作为标签,并给TextView设置背景,通过selector选择器改变其背景颜色,来确定是否处于选中状态. 代码如下所示: 1.标签的布局文件,我在标签里只设置了一个TextView <?xml version="1.0" encoding="utf-8&

随机推荐