用IdleHandler来做闲时等待

MessageQueue类中定义了一个公开静态接口,即IdleHandler

public static interface IdleHandler {
    /**
     * Called when the message queue has run out of messages and will now
     * wait for more.  Return true to keep your idle handler active, false
     * to have it removed.  This may be called if there are still messages
     * pending in the queue, but they are all scheduled to be dispatched
     * after the current time.
     */
    boolean queueIdle();
}

上面的注释的内容大致为:

  • 当消息队列中没有消息,可以使用IdleHandler来等待消息;
  • 返回true表示这个IdleHandler 是激活的,表示一直可以调用,也就是在下次CPU空闲的时候将会调用;
  • 返回false表示移除这个IdleHandler,也就是只调用一次;
  • 如果消息队列中有消息,并且这些消息计算在当前时间之后发送,可以调用IdleHandler

在做启动页的时候,我们可以很粗暴的使用handler来发送一个延迟的消息来做到。但是因为手机性能不同,可能加载时间略有不同。比如:

Handler mHandler = new Handler();
// 5秒后启动主页
mHandler.postDelayed(() -> {
    Intent intent = new Intent();
    intent.setClass(this, MainActivity.class);
}, 5000);

因为延迟启动主要是想在这个时间之内后台完成一些操作,使得页面更加流畅。所以不同设备的时间其实应该不一样。

使用:
这里还是以Glide加载网络上的视频的第一帧图片为例:

// View
ImageView image = findViewById(R.id.image);

Looper looper = Looper.myLooper();  // ActivityThread
MessageQueue queue = looper.getQueue(); 
queue.addIdleHandler(new MessageQueue.IdleHandler() {
    @Override
    public boolean queueIdle() {
        // 使用Glide加载图片
        Glide.with(MergeTestActivity.this)
                .asBitmap()
                .load(Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"))
                .thumbnail((float) 0.3)
                .error(R.drawable.aii)
                .transition(BitmapTransitionOptions.withCrossFade())
                .into(image);
		// 只需要启动一次,返回false
        return false;
    }
});

结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦否

文章对你有用?不妨打赏一毛两毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值