android中延迟执行任务的方式

一:线程延时

       new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    Thread.sleep(3000);//延迟3000毫秒
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                mHandler.sendMessage(message);//发送携带任务的message给主线程执行

<span style="white-space:pre">		</span>或者
                mHandler.sendMessageDelayed(message, 3000);//3000毫秒后发送携带任务的message给主线程执行
            }
        }).start();
<span style="white-space:pre">	</span>
或者
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //要执行的任务
            }
        },3000);
上面三种线程延时的方法底层实现代码差不多都一样
</pre><pre name="code" class="java"></pre><pre name="code" class="java">二:Java API提供的Timer类
</pre><pre name="code" class="java"> <span style="white-space:pre">	</span>TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
            //要执行的任务
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask,3000);//规定任务在3000毫秒后执行

这种定时器使用简单,使用于简单应用场合,但不适用于那些需要长期在后台运行的定时任务

三:Context的AlarmManager

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        int type = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        long triggerAtMillis = SystemClock.elapsedRealtime() + 60 * 60 * 1000;//任务1小时后执行
        PendingIntent operation = PendingIntent.getBroadcast(this, 0, intent, 0);
        alarmManager.set(type, triggerAtMillis, operation);
        /*
        type是AlarmManager的工作类型,表示定时任务的起算时间,可选值ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC
        、RTC_WAKEUP。
        ELAPSED_REALTIME和RTC分别表示系统开机时间和1970年1月1号0点时间,
        ELAPSED_REALTIME_WAKEUP和RTC_WAKEUP分别也表示系统开机时间和1970年1月1号0点时间,但会唤醒CPU

        triggerAtMillis是定时任务的触发时间,使用SystemClock.elapsedRealtime()可以获得系统开机到现在的毫秒数,
        使用System.currentTimeMillis()可以获得1970年1月1号0点到现在的毫秒数

        operation指定要执行的任务行为方式
         */
这种定时器看起来复杂,但功能强大





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值