这篇文章使用AlarmManager实现了Android定时后台循环任务。使用场景:项目需要app每隔一段时间就去服务端请求一次接口,从而更新本地保存的信息。
AlarmManager简介
AlarmManager是Android中常用的一种系统级别的提示服务,在特定的时刻为我们广播一个指定的Intent。简单的说就是我们设定一个时间,然后在该时间到来时,AlarmManager为我们广播一个我们设定的Intent,通常我们使用 PendingIntent。
项目功能简介:
- AlarmService模拟后台任务,定时发起广播
- AlarmReceive启动AlarmService,达到循环启动Service的效果
通过Service和Receiver的死循环,确保后台任务不被系统杀死。
1.AlarmService类
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
|
/** * 一个定时任务 */ public class AlarmService extends Service { /** * 每1分钟更新一次数据 */ private static final int ONE_Miniute= 60 * 1000 ; private static final int PENDING_REQUEST= 0 ; public AlarmService() { } /** * 调用Service都会执行到该方法 */ @Override public int onStartCommand(Intent intent, int flags, int startId) { //这里模拟后台操作 new Thread( new Runnable() { @Override public void run() { Log.e( "wj" , "循环执行了,哈哈." + System.currentTimeMillis()); } }).start(); //通过AlarmManager定时启动广播 AlarmManager alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE); long triggerAtTime=SystemClock.elapsedRealtime()+ONE_Miniute; //从开机到现在的毫秒书(手机睡眠(sleep)的时间也包括在内 Intent i= new Intent( this , AlarmReceive. class ); PendingIntent pIntent=PendingIntent.getBroadcast( this ,PENDING_REQUEST,i,PENDING_REQUEST); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pIntent); return super .onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException( "Not yet implemented" ); } } |
2 AlarmReceive类
1
2
3
4
5
6
7
8
|
public class AlarmReceive extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //循环启动Service Intent i = new Intent(context, AlarmService. class ); context.startService(i); } } |
3 启动Service
1
2
3
4
|
public void startService(View view){ Intent intent= new Intent( this , AlarmService. class ); startService(intent); } |
别忘了AndroidMainfest中注册广播和服务:
1
2
3
4
5
|
< service android:name = ".service.AlarmService" android:enabled = "true" android:exported = "true" /> < receiver android:name = ".receive.AlarmReceive" /> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u014733374/article/details/53413970