在方法 3 使用 Timer 时提示下面信息:
Run multiple TimeTask by using ScheduledExecutorService rather than Timer because Timer will kill all running threads in case of failing to catch exceptions. //org.apache.commons.lang3.concurrent.BasicThreadFactory ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { //do something } },initialDelay,period, TimeUnit.HOURS);所以我们这里修改 Timer 为 ScheduledExecutorService:
private ScheduledExecutorService mExecutorService; public RecyclerViewAdapter(Activity activity, List<Long> itemList) { if (activity == null || itemList == null) { throw new IllegalArgumentException("params can't be null"); } this.activity = activity; this.itemList = itemList; mHolders = new HashSet<>(); mExecutorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { @Override public Thread newThread(@NonNull Runnable r) { Thread thread = new Thread(r); thread.setName("countdown"); return thread; } }); mExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { for (RecyclerViewViewHolder holder : mHolders) { updateTime(holder, holder.getTime()); } } }, 0, 1000, TimeUnit.MILLISECONDS); }全部代码见:https://github.com/nesger/RecyclerView/tree/feature/refresh_4
有更多方法欢迎到上面的 GitHub 链接提 PR,可以基于 feature/refresh 分支新建分支。
有另外一位朋友提出了自定义 View 的处理方式,将倒计时的功能放到 View 里面去处理,这个感兴趣的小伙伴可以实现然后提 PR 哈,这里提供额外一种思路。