android 定时器封装

android 定时器封装好用的定时器封装工具类,谁用谁知道,代码仅供学习参考。importjava.util.HashMap;importjava.util.LinkedList;importjava.util.Map;importjava.util.Queue;importcom.tcl.framework.log.NLog;importandroid.os.Ha

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
好用的定时器封装工具类,谁用谁知道,代码仅供学习参考。

import java.util.HashMap;

import java.util.LinkedList;

import java.util.Map;

import java.util.Queue;

import com.tcl.framework.log.NLog;

import android.os.Handler;

import android.os.HandlerThread;

import android.os.Looper;

import android.os.Message;

public class IoTimer {





public static final int INVALID_TIMER_ID = -1;


private static final int BASE_MSG_ID = 100;


private static volatile IoTimer sTimer = null;


private static final Object slock = new Object();


private TimerHandler mTimerHandler;


private Handler mIoHandler;


private int mBaseTimerId = 1;


private Map<Integer, TimerTask> mTimersList;


private Queue<Integer> mValidIdList = null;


private Looper mIoLooper = null;


private volatile boolean mInited = false;





public static IoTimer shareTimer()


{


if (sTimer == null) {


synchronized (slock) {


if (sTimer == null) {


sTimer = new IoTimer();


sTimer.init();


}


}


}





return sTimer;


}





public static void destroyTimer()


{


if (sTimer != null) {


synchronized (slock) {


final IoTimer timer = sTimer;


if (timer != null) 


timer.destroy();


sTimer = null;


}


}


}





private class TimerTask


{


Runnable action;


int id;


int loopCount;


long expiredTimeout;





void loop()


{


if (loopCount == 0 || loopCount == 1) {


remove(id);


}


else if (loopCount > 1)


loopCount –;





Message msg = mTimerHandler.obtainMessage(messageIdFromTimerId(id), this);


mTimerHandler.sendMessageDelayed(msg, expiredTimeout);


}





void disable()


{


loopCount = 0;


action = null;


mTimerHandler.removeMessages(messageIdFromTimerId(id));


}


}





private IoTimer() {



mTimersList = new HashMap<Integer, IoTimer.TimerTask>();


mValidIdList = new LinkedList<Integer>();


}





private void init() {


if (mInited)


return;






HandlerThread thread = new HandlerThread(“io_timer”) {


@Override


protected void onLooperPrepared() {





mIoLooper = getLooper();


mTimerHandler = new TimerHandler(mIoLooper);


mIoHandler = new Handler(mIoLooper);





mInited = true;


synchronized (IoTimer.this) {


IoTimer.this.notify();


}


}



};



thread.start();


waitToPrepared();



}





private void waitToPrepared() {


synchronized (this) {


while (!mInited) {


try {


wait(10);


} catch (InterruptedException e) {


break;


}


}


}



}





private void destroy() {


if (!mInited)


return;





clear();


mInited = false;


mIoLooper.quit();



}





public boolean resetTimer(int tid, long timeout)


{


TimerTask task = null;


synchronized (this) {


task = mTimersList.get(tid);


}





if (task == null)


return false;





int mid = messageIdFromTimerId(tid);


mTimerHandler.removeMessages(mid);


task.expiredTimeout = timeout;


Message msg = mTimerHandler.obtainMessage(mid, task);


mTimerHandler.sendMessageDelayed(msg, task.expiredTimeout);


return true;


}





public boolean resetTimer(int tid)


{


if (!mInited)


throw new IllegalStateException(“not inited”);





TimerTask task = null;


synchronized (this) {


task = mTimersList.get(tid);


}





if (task == null)


return false;





int mid = messageIdFromTimerId(tid);


mTimerHandler.removeMessages(mid);


Message msg = mTimerHandler.obtainMessage(mid, task);


mTimerHandler.sendMessageDelayed(msg, task.expiredTimeout);


return true;


}





public int scheduleTimer(long timeout, Runnable action)


{


return scheduleTimer(timeout, action, 1, timeout);


}





public int scheduleTimer(long timeout, Runnable action, int loop, long delay) {


if (timeout < 0 || action == null || loop == 0)


throw new IllegalArgumentException(“timeout is invalid, or action is null, or loop is 0!”);





if (!mInited)


throw new IllegalStateException(“not inited”);





int id = nextTimerId();


if (id == -1) {


return INVALID_TIMER_ID;


}





TimerTask tt = new TimerTask();


tt.id = id;


tt.expiredTimeout = timeout;


tt.action = action;


tt.loopCount = loop;





synchronized (this) {


mTimersList.put(id, tt);


}


Message msg = mTimerHandler.obtainMessage(messageIdFromTimerId(id), tt);


mTimerHandler.sendMessageDelayed(msg, delay);


return id;


}





private synchronized TimerTask remove(int tid)


{


TimerTask ret = null;


ret = mTimersList.remove(tid);


if (!mValidIdList.contains(tid)) {


if (!mValidIdList.offer(tid)){


NLog.e(“TimerTask”, “offer fail”);


}


}





return ret;


}





private synchronized boolean hasTimer(int tid)


{


return mTimersList.containsKey(tid);


}





public void cancelTimer(int tid)


{


TimerTask task = remove(tid);


if (task == null)


return;





task.disable();


}





public synchronized void clear()


{


mValidIdList.clear();


mTimersList.clear();



mBaseTimerId = 1;


}





protected synchronized int nextTimerId() {


if (mValidIdList.size() == 0)


return mBaseTimerId++;


int id = mValidIdList.poll();


return id;


}





private int messageIdFromTimerId(int id)


{


return (BASE_MSG_ID + id);


}





protected void onTimer(TimerTask task) {


final Runnable action = task.action;


if (action != null) { 


action.run();


}


}





class TimerHandler extends Handler


{


public TimerHandler(Looper looper) {


super(looper);


}


@Override


public void handleMessage(Message msg) {


if (msg.what < BASE_MSG_ID)


return;





TimerTask task = (TimerTask) msg.obj;


if (hasTimer(task.id)) {


mIoHandler.post(new TimerRunnable(task));


task.loop();


}



}


}








private class TimerRunnable implements Runnable


{


final TimerTask task;


public TimerRunnable(final TimerTask tt) {


this.task = tt;


}





@Override


public void run() {


onTimer(task);


}





}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/160037.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • spark中flatMap函数用法–spark学习(基础)「建议收藏」

    spark中flatMap函数用法–spark学习(基础)「建议收藏」说明在spark中map函数和flatMap函数是两个比较常用的函数。其中map:对集合中每个元素进行操作。flatMap:对集合中每个元素进行操作然后再扁平化。理解扁平化可以举个简单例子valarr=sc.parallelize(Array((“A”,1),(“B”,2),(“C”,3)))arr.flatmap(x=>(x._1+x._2)).foreach(println)输出

    2022年5月27日
    34
  • TCP/IP协议详解 卷1 Traceroute程序[通俗易懂]

    TCP/IP协议详解 卷1 Traceroute程序[通俗易懂]作用可以让我们看到IP数据报从1台主机传到另一台主机所经过的路由。比Ping程序看到更多东西优势不是所有路由器都支持RR选项。所以有些路由器上会出现不记录IP的现象。Traceroute不需要路由器具备任何特殊的功能RR选项的数据报的目的Ping服务器(主机)会将接受到的RR清单Copy回去。然后再加上回去的IP清单。这样就是X2。这会收到一些限制IP首部的空间有限,不能存放太多的IP…

    2022年6月20日
    28
  • portraiture mac智能磨皮滤镜

    portraiture mac智能磨皮滤镜portraiture3Mac版是一款MacOS平台基于原始肖像插件的核心技术和功能集的PS智能磨皮滤镜软件,portraituremac将您的皮肤修饰工作流程提升到更高的性能水平,结果质量和整体易用性。我们敢说,我们的portraiture滤镜插件将继续改变行业,实现几乎所有技能水平,在图像主题和生产挑战的范围内实现卓越的皮肤修饰,包括肖像,全身,团体拍摄,广告,时尚,美容,医疗和运动图像,没有与其他软件产品,插件或数字修饰技术相关的熟悉约束或学习曲线。portraituremac可以出色的完成磨

    2022年7月22日
    8
  • 编译器指令重排和CPU指令重排_十进制调整指令DA怎么用

    编译器指令重排和CPU指令重排_十进制调整指令DA怎么用这个知识点也是很多人说不清道不明的地方,感觉都知道,说又说不出来。为什么会这样呢?因为这几个字,很容易被当成动词去理解,其实正确的理解是当成名词,即指令重排现象。那什么时候会产生指令重排现象呢?两个阶段:1、编译期;2、运行期。编译期指令重排解释型语言是在运行期间执行编译+运行动作,所以运行效率较编译型语言低。Java既可以作为解释型语言去用,也可以作为编译型语言。但是主流的做法是当成编译型语言在…

    2022年10月8日
    3
  • clientheight什么意思_document.body.clientheight

    clientheight什么意思_document.body.clientheight转载自:https://www.imooc.com/article/17571网页可见区域高:document.body.clientHeight网页正文全文高:document.body.scrollHeight网页可见区域高(包括边线的高):document.body.offsetHeight网页被卷去的高:document.body.scrollTop屏幕分辨率高:window.s…

    2025年8月29日
    8
  • let/const 的变量提升与暂时性死区

    let/const 的变量提升与暂时性死区在面试或一些文章中提到var和let/const区别时,总说var有变量提升,let/const不存在变量提升,这种说法是错误的.var和let/const都有变量提升,但是let/const暂时性死区的存在要求调用该类变量前必须先经过显式赋值

    2022年6月23日
    50

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号