Android 创建线程执行任务
16lz
2021-01-23
一、新建CommonWorkingThread类,如下:
import android.os.Handler;import android.os.HandlerThread;import android.util.Log;public class CommonWorkingThread {private static HandlerThread thread = null;private static Handler handler = null;private CommonWorkingThread() {}public static class CommonWorkingThreadHolder {public static CommonWorkingThread instance = new CommonWorkingThread();}public static CommonWorkingThread getInstance() {initHandler();return CommonWorkingThreadHolder.instance;}public boolean execute(Runnable r) {if (handler != null) {Log.i("CommonWorkingThread", ">>> working thread execute ");return handler.post(r);}return false;}public boolean execute(Runnable r, long delayMillis) {if (handler != null) {Log.i("CommonWorkingThread",">>> working thread execute delayMillis " + delayMillis);return handler.postDelayed(r, delayMillis);}return false;}public Handler getHandler() {return handler;}private static void initHandler() {if (thread == null || !thread.isAlive() || thread.isInterrupted()|| thread.getState() == Thread.State.TERMINATED) {thread = new HandlerThread("tpush.working.thread");thread.start();handler = new Handler(thread.getLooper());Log.i("CommonWorkingThread", ">>> Create new working thread."+ thread.getId());}}}二、在需要用到的地方按如下调用方式调用:
CommonWorkingThread.getInstance().execute(new Runnable() {@Overridepublic void run() {//在此执行具体任务}}, 100L); // 100L位delay执行的时间
更多相关文章
- Android关于桌面快捷方式工具类!
- ch07 Android 日期与时间对话框
- Android TimeLine 时间节点轴的实现
- Android时间工具类 本地转UTC,UTC转本地
- Android菜单实现两种方式
- 我今天的面试题,注册广播有几种方式,这些方式有何优缺点?请谈谈Andr
- Android 代码设置Color的几种方式
- Android控件隐藏方式 .