Repeating Periodic Tasks in Android
来源:互联网 发布:淘宝保存的图片找不到 编辑:程序博客网 时间:2024/06/06 03:44
Overview
Repeating periodic tasks within an application is a common requirement. This functionality can be used for polling new data from the network, running manual animations, or simply updating the UI. There are at least four ways to run periodic tasks:
- Handler - Execute a
Runnable
task on the UIThread after an optional delay - ScheduledThreadPoolExecutor - Execute periodic tasks with a background thread pool
- AlarmManager - Execute any periodic task in the background as a service
- TimerTask - Doesn't run in UIThread and is not reliable. Consensus is to never use TimerTask
Recommended methods are outlined below.
Handler
We can use a Handler to run code on a given thread after a delay or repeat tasks periodically on a thread. This is done by constructing a Handler
and then "posting" Runnable
code to the event message queue on the thread to be processed.
Executing Code After Delay
Using a Handler
, we can execute arbitrary code a single time after a specified delay:
// We need to use this Handler packageimport android.os.Handler;// Create the Handler object (on the main thread by default)Handler handler = new Handler();// Define the code block to be executedprivate Runnable runnableCode = new Runnable() { @Override public void run() { // Do something here on the main thread Log.d("Handlers", "Called on main thread"); }};// Run the above code block on the main thread after 2 secondshandler.postDelayed(runnableCode, 2000);
Execute Recurring Code with Specified Interval
Using a similar technique, we can also use a handler to execute a periodic runnable task as demonstrated below:
// We need to use this Handler packageimport android.os.Handler;// Create the Handler object (on the main thread by default)Handler handler = new Handler();// Define the code block to be executedprivate Runnable runnableCode = new Runnable() { @Override public void run() { // Do something here on the main thread Log.d("Handlers", "Called on main thread"); // Repeat this the same runnable code block again another 2 seconds // 'this' is referencing the Runnable object handler.postDelayed(this, 2000); }};// Start the initial runnable task by posting through the handlerhandler.post(runnableCode);
We can remove the scheduled execution of a runnable with:
// Removes pending code executionhandler.removeCallbacks(runnableCode);
Note that with a Handler
, the Runnable
executes in UIThread
by default so you can safely update the user interface within the runnable code block. See this handler post and this other handler post for reference.
Refer to our threads and handlers guide for a more advanced breakdown.
ScheduledThreadPoolExecutor
A pool of threads which can schedule commands to execute periodically in the background. Useful when multiple worker threads are needed but generally not needed. See this guide on how they work or this stackoverflow post.
AlarmManager
This should be used if the periodic tasks need to run in the background even when the app is not in the foreground. This leverages the alarm service on the phone to cause periodic executions of a service which will run continuously until stopped. See the AlarmManager section of the services guide for details.
References
- http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/
- http://stackoverflow.com/questions/18605403/timertask-vs-thread-sleep-vs-handler-postdelayed-most-accurate-to-call-functio
- http://androidtrainningcenter.blogspot.in/2013/12/handler-vs-timer-fixed-period-execution.html
- http://stackoverflow.com/questions/8098806/where-do-i-create-and-use-scheduledthreadpoolexecutor-timertask-or-handler
- Repeating Periodic Tasks in Android
- Schedule periodic tasks in Java
- How to implement realtime periodic tasks in Linux applications
- Periodic Tasks - Linux
- nova-compute Periodic tasks 机制
- Celery-4.1 用户指南: Periodic Tasks
- Uncaught exceptions in scheduled tasks
- Periodic Processing in Axapta, Part I
- Android 管理Tasks
- Android Activity和Tasks
- tasks
- android Tasks and Back Stack
- Android Tasks and Back Stack
- Android-Tasks and Back Stack
- Android 下的 bolts tasks
- Android-Tasks and Back Stack
- Android - 《Tasks and Back Stack》
- Android Tasks、ActivityStack和Activity
- ArcGIS实现聚合点效果
- boost安装 c++
- AOP
- 关于dsp28335移相全桥
- Java的循环结构
- Repeating Periodic Tasks in Android
- try-catch-finally中throw,return时的执行顺序
- Redmine与Gitlab深度集成
- hive无法执行带where语句的SQL
- 优达机器学习:回归
- 管理maven项目,隔离开发环境数据库与生产环境数据库
- myabties 符号缺少
- springcloud-hystrix容错保护注解方式的使用
- Spring Boot系列(九) Spring Boot集成Sorl搜索客户端