前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >android 定时器封装

android 定时器封装

作者头像
全栈程序员站长
发布2022-09-15 10:10:17
3550
发布2022-09-15 10:10:17
举报

大家好,又见面了,我是你们的朋友全栈君。 好用的定时器封装工具类,谁用谁知道,代码仅供学习参考。

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.cn/160037.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
物联网
腾讯连连是腾讯云物联网全新商业品牌,它涵盖一站式物联网平台 IoT Explorer,连连官方微信小程序和配套的小程序 SDK、插件和开源 App,并整合腾讯云内优势产品能力,如大数据、音视频、AI等。同时,它打通腾讯系 C 端内容资源,如QQ音乐、微信支付、微保、微众银行、医疗健康等生态应用入口。提供覆盖“云-管-边-端”的物联网基础设施,面向“消费物联”和 “产业物联”两大赛道提供全方位的物联网产品和解决方案,助力企业高效实现数字化转型。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档