android中延迟执行任务的方式

来源:互联网 发布:js 对象数组 查找元素 编辑:程序博客网 时间:2024/06/05 03:36

一:线程延时

       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
原创粉丝点击