App 启动页倒计时 3 秒跳转到 App 的首页, 这种操作在很多 App 中都很常见. 如果需要做一个延时操作呢? 写一个子线程停留 3 秒然后执行操作, 这样的话需要特别的注意的是 UI 操作必须放在主线程里, 那么还需要转化成主线程? NO, 使用 Handler 轻松实现倒计时和延时操作.
一. 启动页倒计时详细操作
- private int duration = 6;
- private Handler updateHandler = new Handler() {
- @Override
- public void dispatchMessage(Message msg) {
- super.dispatchMessage(msg);
- if (msg.what == 2) {
- if (duration> 0) {
- duration--;
- appStartBinding.jumpButton.setText(duration + "s 跳过");
- if (duration == 1) {
- // 用户自己的操作
- }
- updateHandler.sendEmptyMessageDelayed(2, 1000);
- }
- }
- }
- };
- // 在需要倒计时的地方执行以下代码
- updateHandler.sendEmptyMessage(2);
二. 延时操作
使用 Handler 做延时请求, 无需担心 UI 线程是否在主线程
- private Handler updateHandler = new Handler() {
- @Override
- public void dispatchMessage(Message msg) {
- super.dispatchMessage(msg);
- if (msg.what == 14) {
- // 用户自己的操作
- }
- }
- };
- // 在需要延时操作的地方执行以下代码
- /**
- * 第一参数: what
- * 第二个参数: 需要延时的毫秒数
- */
- updateHandler.sendEmptyMessageDelayed(14, 2000);
以上实现倒计时和延时操作, 不要忘记在 Activity 的 onDestroy() 方法里移除.
- if (updateHandler != null) {
- updateHandler.removeCallbacksAndMessages(null);
- }
以上就是 Android 里简单实用的倒计时跳转和延时操作的具体步骤和代码, 实现倒计时和延时操作有很多种, 具体的还是需要看能否满足自己的需求.
来源: http://www.jianshu.com/p/7863e63d39a7