在Android开发中,定时执行任务的3种实现方法:
一、采用Handler与线程的sleep(long)方法(不建议使用,Jva的实现方式)
二、采用Handler的postDelayed(Runnable, long)方法(最简单的android实现)
三、采用Handler与timer及TimerTask结合的方法(比较多的任务时建议使用)
Android消息机制
首先来了解一下Android的消息处理机制
即Handlerd的运行机制,handler的运行需要底层的MessageQueue和Looper的支撑。MessageQueue(消息队列),它的内部存储了一些消息,以队列的形式对外提供插入和删除的操作(实际为单链表存储)。Looper(消息循环),配合MessageQueue实现实现消息的不断入队和出队工作。
一个关系图:
通过Handler可以很容易将任务切换到其他线程中执行,以减少主线程的负担,因此Handler常用来进行UI更新。这里只是简单的进行一些概述。
当然,现在已经有更好的消息处理办法了,了解handler和Asynctask可以更好的理解Android内部消息的处理机制。
推荐:EventBus,高度解耦,代码简洁明了,有兴趣的可以自行参考使用。
1.采用Handle与线程的sleep(long)方法
1) 定义一个Handler类,用于处理接受到的Message。
1
2
3
4
5
6
|
Handler handler =
new
Handler() {
public
void
handleMessage(Message msg) {
// 要做的事情
super
.handleMessage(msg);
}
};
|
2) 新建一个实现Runnable接口的线程类,如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
MyThread
implements
Runnable {
@Override
public
void
run() {
// TODO Auto-generated method stub
while
(
true
) {
try
{
Thread.sleep(
10000
);
// 线程暂停10秒,单位毫秒
Message message =
new
Message();
message.what =
1
;
handler.sendMessage(message);
// 发送消息
}
catch
(InterruptedException e) {
e.printStackTrace();
}
} } }
|
3) 在需要启动线程的地方加入下面语句:
1
|
new
Thread(
new
MyThread()).start();
|
分析:纯正的java原生实现,在sleep结束后,并不能保证竞争到cpu资源,这也就导致了时间上必定>=10000的精度问题。
2.采用Handler的postDelayed(Runnable, long)方法
1)定义一个Handler类
1
2
3
4
5
6
7
8
9
10
11
|
Handler handler=
new
Handler();
Runnable runnable=
new
Runnable() {
@Override
public
void
run() {
// TODO Auto-generated method stub
//要做的事情
handler.postDelayed(
this
,
2000
);
}
};
|
2) 启动与关闭计时器
1
2
|
handler.postDelayed(runnable,
2000
);
//每两秒执行一次runnable.
handler.removeCallbacks(runnable);
|
分析:嗯,看起蛮不错,实现上也简单了,和sleep想必还不会产生阻塞,注意等待和间隔的区别。
3.采用Handler与timer及TimerTask结合的方法
1) 定义定时器、定时器任务及Handler句柄
1
2
3
4
5
6
7
8
9
10
|
private
final
Timer timer =
new
Timer();
private
TimerTask task;
Handler handler =
new
Handler() {
@Override
public
void
handleMessage(Message msg) {
// TODO Auto-generated method stub
// 要做的事情
super
.handleMessage(msg);
}
};
|
2) 初始化计时器任务
1
2
3
4
5
6
7
8
9
|
task =
new
TimerTask() {
@Override
public
void
run() {
// TODO Auto-generated method stub
Message message =
new
Message();
message.what =
1
;
handler.sendMessage(message);
}
};
|
3) 启动和关闭定时器
1
2
|
timer.schedule(task,
2000
,
3000
);
timer.cancel();
|
此外,Timer也可以配合runOnUiThread实现,如下
1
2
3
4
5
6
7
8
9
10
11
12
|
private
TimerTask mTimerTask =
new
TimerTask() {
@Override
public
void
run() {
runOnUiThread(
new
Runnable() {
@Override
public
void
run() {
//处理延时任务
}
});
}
};
|
分析:timer.schedule(task, 2000, 3000);意思是在2秒后执行第一次,之后每3000秒在执行一次。timer不保证精确度且在无法唤醒cpu,不适合后台任务的定时。
采用AlarmManger实现长期精确的定时任务
AlarmManager的常用方法有三个:
set(int type,long startTime,PendingIntent pi);//一次性setExact(int type, long triggerAtMillis, PendingIntent operation)//一次性的精确版setRepeating(int type,long startTime,long intervalTime,PendingIntent
pi);//精确重复setInexactRepeating(int type,long startTime,long
intervalTime,PendingIntent pi);//非精确,降低功耗
type表示闹钟类型,startTime表示闹钟第一次执行时间,long intervalTime表示间隔时间,PendingIntent表示闹钟响应动作
对以上各个参数的详细解释
闹钟的类型:
AlarmManager.ELAPSED_REALTIME:休眠后停止,相对开机时间AlarmManager.ELAPSED_REALTIME_WAKEUP:休眠状态仍可唤醒cpu继续工作,相对开机时间AlarmManager.RTC:同1,但时间相对于绝对时间AlarmManager.RTC_WAKEUP:同2,但时间相对于绝对时间AlarmManager.POWER_OFF_WAKEUP:关机后依旧可用,相对于绝对时间
startTime:
闹钟的第一次执行时间,以毫秒为单位,一般使用当前时间。
SystemClock.elapsedRealtime():系统开机至今所经历时间的毫秒数System.currentTimeMillis():1970 年 1 月 1 日 0 点至今所经历时间的毫秒数
intervalTime:执行时间间隔。
PendingIntent :
PendingIntent用于描述Intent及其最终的行为.,这里用于获取定时任务的执行动作。
利用AlarmManger+Service+BarocastReceiver实现5s一次打印操作
服务类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<code>
public
class
HorizonService
extends
Service {
@Override
public
IBinder onBind(Intent intent) {
return
null
;
}
@Override
public
int
onStartCommand(Intent intent,
int
flags,
int
startId) {
new
Thread(
new
Runnable() {
@Override
public
void
run() {
Log.d(
"TAG"
,
"打印时间: "
+
new
Date().
toString());
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int
five =
5000
;
// 这是5s
long
triggerAtTime = SystemClock.elapsedRealtime() + five;
Intent i =
new
Intent(
this
, AlarmReceiver.
class
);
PendingIntent pi = PendingIntent.getBroadcast(
this
,
0
, i,
0
);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return
super
.onStartCommand(intent, flags, startId);
}
}</code>
|
广播接受器
1
2
3
4
5
6
7
|
<code>
public
class
AlarmReceiver
extends
BroadcastReceiver {
@Override
public
void
onReceive(Context context, Intent intent) {
Intent i =
new
Intent(context, HorizonService.
class
);
context.startService(i);
}
}</code>
|
启动定时任务:
1
2
|
<code>Intent intent =
new
Intent(
this
,HorizonService.
class
);
startService(intent);</code>
|
效果Demo:
本例通过广播接收器和服务的循环调用实现了无限循环的效果,当然,你也可以直接利用setRepeating实现同样的效果。
注意:不要忘了在manifest文件中注册服务和广播接收器。
AlarmManager的取消方法:AlarmManger.cancel();
分析:该方式可唤醒cpu甚至实现精确定时,适用于配合service在后台执行一些长期的定时行为。
前言
项目中总是会因为各种需求添加各种定时任务,所以就打算小结一下Android中如何实现定时任务,下面的解决方案的案例大部分都已在实际项目中实践,特此列出供需要的朋友参考,如果有什么使用不当或者存在什么问题,欢迎留言指出!直接上干货!
解决方案
普通线程sleep的方式实现定时任务
创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果,这是最常见的,可以快速简单地实现。但是这是java中的实现方式,不建议使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<code>
public
class
ThreadTask {
public
static
void
main(String[] args) {
final
long
timeInterval =
1000
;
Runnable runnable =
new
Runnable() {
public
void
run() {
while
(
true
) {
System.out.println(
"execute task"
);
try
{
Thread.sleep(timeInterval);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread =
new
Thread(runnable);
thread.start();
}
} </code>
|
Timer实现定时任务
和普通线程+sleep(long)+Handler的方式比,优势在于
可以控制TimerTask的启动和取消第一次执行任务时可以指定delay的时间。
在实现时,Timer类调度任务,TimerTask则是通过在run()方法里实现具体任务(然后通过Handler与线程协同工作,接收线程的消息来更新主UI线程的内容)。
Timer实例可以调度多任务,它是线程安全的。当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<code>
/**
* start Timer
*/
protected
synchronized
void
startPlayerTimer() {
stopPlayerTimer();
if
(playTimer ==
null
) {
playTimer =
new
PlayerTimer();
Timer m_musictask =
new
Timer();
m_musictask.schedule(playTimer,
5000
,
5000
);
}
}
/**
* stop Timer
*/
protected
synchronized
void
stopPlayerTimer() {
try
{
if
(playTimer !=
null
) {
playTimer.cancel();
playTimer =
null
;
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
public
class
PlayerTimer
extends
TimerTask {
public
PlayerTimer() {
}
public
void
run() {
//execute task
}
}</code>
|
然而Timer是存在一些缺陷的
Timer在执行定时任务时只会创建一个线程,所以如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会发生一些缺陷如果Timer调度的某个TimerTask抛出异常,Timer会停止所有任务的运行Timer执行周期任务时依赖系统时间,修改系统时间容易导致任务被挂起(如果当前时间小于执行时间)
注意:
Android中的Timer和java中的Timer还是有区别的,但是大体调用方式差不多Android中需要根据页面的生命周期和显隐来控制Timer的启动和取消
java中Timer:
Android中的Timer:
ScheduledExecutorService实现定时任务
ScheduledExecutorService是从JDK1.5做为并发工具类被引进的,存在于java.util.concurrent,这是最理想的定时任务实现方式。
相比于上面两个方法,它有以下好处:
相比于Timer的单线程,它是通过线程池的方式来执行任务的,所以可以支持多个任务并发执行 ,而且弥补了上面所说的Timer的缺陷可以很灵活的去设定第一次执行任务delay时间 提供了良好的约定,以便设定执行的时间间隔
简例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<code>
public
class
ScheduledExecutorServiceTask
{
public
static
void
main(String[] args)
{
final
TimerTask task =
new
TimerTask()
{
@Override
public
void
run()
{
//execute task
}
};
ScheduledExecutorService pool = Executors.newScheduledThreadPool(
1
);
pool.scheduleAtFixedRate(task,
0
,
1000
, TimeUnit.MILLISECONDS);
}
}</code>
|
实际案例背景:
应用中多个页面涉及比赛信息展示(包括比赛状态,比赛结果),因此需要实时更新这些数据
思路分析:
多页面多接口刷新
就是每个需要刷新的页面基于自身需求基于特定接口定时刷新每个页面要维护一个定时器,然后基于页面的生命周期和显隐进行定时器的开启和关闭(保证资源合理释放)而且这里的刷新涉及到是刷新局部数据还是整体数据,刷新整体数据效率会比较低,显得非常笨重 多页面单接口刷新
接口给出一组需要实时进行刷新的比赛数据信息,客户端基于id进行统一过滤匹配通过单例封装统一定时刷新回调接口(注意内存泄露的问题,页面销毁时关闭ScheduledExecutorService )需要刷新的item统一调用,入口唯一,方便维护管理,扩展性好局部刷新,效率高
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
<code>
public
class
PollingStateMachine
implements
INetCallback {
private
static
volatile
PollingStateMachine instance =
null
;
private
ScheduledExecutorService pool;
public
static
final
int
TYPE_MATCH =
1
;
private
Map matchMap =
new
HashMap<>();
private
List<weakreference<view>> list =
new
ArrayList<>();
private
Handler handler;
// private constructor suppresses
private
PollingStateMachine() {
defineHandler();
pool = Executors.newSingleThreadScheduledExecutor();
pool.scheduleAtFixedRate(
new
Runnable() {
@Override
public
void
run() {
doTasks();
}
},
0
,
10
, TimeUnit.SECONDS);
}
private
void
doTasks() {
ThreadPoolUtils.execute(
new
PollRunnable(
this
));
}
public
static
PollingStateMachine getInstance() {
// if already inited, no need to get lock everytime
if
(instance ==
null
) {
synchronized
(PollingStateMachine.
class
) {
if
(instance ==
null
) {
instance =
new
PollingStateMachine();
}
}
}
return
instance;
}
public
<view
extends
=
""
view=
""
>
void
subscibeMatch(VIEW view, OnViewRefreshStatus onViewRefreshStatus) {
subscibe(TYPE_MATCH,view,onViewRefreshStatus);
}
private
<view
extends
=
""
view=
""
>
void
subscibe(
int
type, VIEW view, OnViewRefreshStatus onViewRefreshStatus) {
view.setTag(onViewRefreshStatus);
if
(type == TYPE_MATCH) {
onViewRefreshStatus.update(view, matchMap);
}
for
(WeakReference<view> viewSoftReference : list) {
View textView = viewSoftReference.get();
if
(textView == view) {
return
;
}
}
WeakReference<view> viewSoftReference =
new
WeakReference<view>(view);
list.add(viewSoftReference);
}
public
void
updateView(
final
int
type) {
Iterator<weakreference<view>> iterator = list.iterator();
while
(iterator.hasNext()) {
WeakReference<view> next = iterator.next();
final
View view = next.get();
if
(view ==
null
) {
iterator.remove();
continue
;
}
Object tag = view.getTag();
if
(tag ==
null
|| !(tag
instanceof
OnViewRefreshStatus)) {
continue
;
}
final
OnViewRefreshStatus onViewRefreshStatus = (OnViewRefreshStatus) tag;
handler.post(
new
Runnable() {
@Override
public
void
run() {
if
(type == TYPE_MATCH) {
onViewRefreshStatus.update(view, matchMap);
}
}
});
}
}
public
void
clear() {
pool.shutdown();
instance =
null
;
}
private
Handler defineHandler() {
if
(handler ==
null
&& Looper.myLooper() == Looper.getMainLooper()) {
handler =
new
Handler();
}
return
handler;
}
@Override
public
void
onNetCallback(
int
type, Map msg) {
if
(type == TYPE_MATCH) {
matchMap=msg;
}
updateView(type);
}
}</view></weakreference<view></view></view></view></view></view></weakreference<view></code>
|
需要刷新的item调用
1
2
3
4
5
6
|
<code>PollingStateMachine.getInstance().subscibeMatch(tvScore,
new
OnViewRefreshStatus<scoreitem, textview=
""
>(matchViewItem.getMatchID()) {
@Override
public
void
OnViewRefreshStatus(TextView view, ScoreItem scoreItem) {
//刷新处理
}
});</scoreitem,></code>
|
网络数据回调接口
1
2
|
<code>
public
interface
INetCallback {
void
onNetCallback(
int
type,Map msg);}</code>
|
刷新回调接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<code>
public
abstract
class
OnViewRefreshStatus<value,
extends
=
""
view=
""
> {
private
static
final
String TAG = OnViewRefreshStatus.
class
.getSimpleName();
private
long
key;
public
OnViewRefreshStatus(
long
key) {
this
.key = key;
}
public
long
getKey() {
return
key;
}
public
void
update(
final
VIEW view, Map<
long
, value=
""
> map) {
final
VALUE value = map.get(key);
if
(value ==
null
) {
return
;
}
OnViewRefreshStatus(view, value);
}
public
abstract
void
OnViewRefreshStatus(VIEW view, VALUE value);
}</
long
,></value,></code>
|
Handler实现定时任务
通过Handler延迟发送消息的形式实现定时任务。
这里通过一个定时发送socket心跳包的案例来介绍如何通过Handler完成定时任务
案例背景
由于移动设备的网络的复杂性,经常会出现网络断开,如果没有心跳包的检测, 客户端只会在需要发送数据的时候才知道自己已经断线,会延误,甚至丢失服务器发送过来的数据。 所以需要提供心跳检测
下面的代码只是用来说明大体实现流程
WebSocket初始化成功后,就准备发送心跳包每隔30s发送一次心跳创建的时候初始化Handler,销毁的时候移除Handler消息队列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<code>
private
static
final
long
HEART_BEAT_RATE =
30
*
1000
;
//目前心跳检测频率为30s
private
Handler mHandler;
private
Runnable heartBeatRunnable =
new
Runnable() {
@Override
public
void
run() {
// excute task
mHandler.postDelayed(
this
, HEART_BEAT_RATE);
}
};
public
void
onCreate() {
//初始化Handler
}
//初始化成功后,就准备发送心跳包
public
void
onConnected() {
mHandler.removeCallbacks(heartBeatRunnable);
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
}
public
void
onDestroy() {
mHandler.removeCallbacks(heartBeatRunnable)
}</code>
|
注意:这里开启的runnable会在这个handler所依附线程中运行,如果handler是在UI线程中创建的,那么postDelayed的runnable自然也依附在主线程中。
AlarmManager实现精确定时操作
我们使用Timer或者handler的时候会发现,delay时间并没有那么准。如果我们需要一个严格准时的定时操作,那么就要用到AlarmManager,AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service.
案例背景
在比赛开始前半个小时本地定时推送关注比赛的提醒信息
AndroidManifest.xml中声明一个全局广播接收器
1
2
3
4
5
|
<code> <receiver android:exported=
"false"
android:name=
".receiver.AlarmReceiver"
>
<intent-filter>
</action></intent-filter>
</receiver></code>
|
接收到action为IntentConst.Action.matchRemind的广播就展示比赛
提醒的Notification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<code>
public
class
AlarmReceiver
extends
BroadcastReceiver {
private
static
final
String TAG =
"AlarmReceiver"
;
@Override
public
void
onReceive(Context context, Intent intent) {
if
(intent ==
null
) {
return
;
}
String action = intent.getAction();
if
(TextUtils.equals(action, IntentConst.Action.matchRemind)) {
//通知比赛开始
long
matchID = intent.getLongExtra(Net.Param.ID,
0
);
showNotificationRemindMe(context, matchID);
}
}
}</code>
|
AlarmUtil提供设定闹铃和取消闹铃的两个方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<code>
public
class
AlarmUtil {
private
static
final
String TAG =
"AlarmUtil"
;
public
static
void
controlAlarm(Context context,
long
startTime,
long
matchId, Intent nextIntent) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, (
int
) matchId, nextIntent,
PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP, startTime, pendingIntent);
}
public
static
void
cancelAlarm(Context context, String action,
long
matchId) {
Intent intent =
new
Intent(action);
PendingIntent sender = PendingIntent.getBroadcast(
context, (
int
) matchId, intent,
0
);
// And cancel the alarm.
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}}</code>
|
关注比赛的时候,会设置intent的action为IntentConst.Action.matchRemind,会根据比赛的开始时间提前半小时设定闹铃时间,取消关注比赛同时取消闹铃
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<code>
if
(isSetAlarm) {
long
start_tm = matchInfo.getStart_tm();
long
warmTime = start_tm -
30
*
60
;
Intent intent =
new
Intent(IntentConst.Action.matchRemind);
intent.putExtra(Net.Param.ID, matchInfo.getId());
AlarmUtil.controlAlarm(context, warmTime *
1000
,matchInfo.getId(), intent);
Gson gson =
new
Gson();
String json = gson.toJson(matchInfo);
SportDao.getInstance(context).insertMatchFollow(eventID, matchInfo.getId(), json, matchInfo.getType());
}
else
{
AlarmUtil.cancelAlarm(context, IntentConst.Action.matchRemind,matchInfo.getId());
SportDao.getInstance(context).deleteMatchFollowByID(matchInfo.getId());
}</code>
|