---
title: "Android AlarmManager实现不间断轮询服务 "
author: "hack_zhang"
date: "2013-07-17T10:48:34Z"
tags: []
categories: ["移动开发"]
slug: "android-alarmmanager"
draft: false
lastmod: "2013-07-17T11:03:56Z"
id: 1908241
url: "https://hack-zhang.iteye.com/blog/1908241"
---

在消息的获取上是选择轮询还 是推送得根据实际的业务需要来技术选型，例如对消息实时性比较高的需求，比如微博新通知或新闻等那就最好是用推送了。但如果只是一般的消息检测比如更新检 查，可能是半个小时或一个小时一次，那用轮询也是一个不错的选择，因为不需要额外搭建推送服务器，不用额外配置推送服务。另外推送现在一般以维持长连接的 方式实现，在手机客户端也会耗费一定的电量。今天就介绍一个在Android上实现轮询机制的方法——使用AlarmManager

 

AlarmManager在 Android中主要用来定时处理一个事件或是定期处理一个事件，比如闹钟应用就是使用AlarmManager来实现的，我们今天要使用 AlarmManager的定期执行功能来实现轮询的功能。对于定期执行任务也可以用Timer和TimerTask来实现，也可以开一个Service 在Thread里面以while循环来实现。但最好的方案还是选用AlarmManager，这里涉及一个Android系统锁的机制，即系统在检测到一 段时间没有活跃以后，会关闭一些不必要的服务来减少资源和电量消耗。使用Timer和Service来实现的话很可能出现的情况就是屏幕熄灭后一段时间， 服务就被停止了，当然轮询也就被停止了。这个大家可以实验一下，之前我写过一篇文章也介绍了一种保持后台唤醒的机制《[使用WakeLock使Android应用程序保持后台唤醒](/admin/blogs/1908252)》，感兴趣的可以看看。那么接下来就开始使用AlarmManager+Service+Thread来实现我们的轮询服务吧！

 

 

 

**一、新建轮询工具类PollingUtils.java**

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/9317499 "view plain")[copy](http://blog.csdn.net/tangren03/article/details/9317499 "copy")

01. public class PollingUtils {
02. //开启轮询服务
03. public static void startPollingService(Context context, int seconds, Class&lt;?&gt; cls,String action) {
04. //获取AlarmManager系统服务
05. AlarmManager manager = (AlarmManager) context
06. .getSystemService(Context.ALARM\_SERVICE);
07. //包装需要执行Service的Intent
08. Intent intent = new Intent(context, cls);
09. intent.setAction(action);
10. PendingIntent pendingIntent = PendingIntent.getService(context, 0,
11. intent, PendingIntent.FLAG\_UPDATE\_CURRENT);
12. //触发服务的起始时间
13. long triggerAtTime = SystemClock.elapsedRealtime();
14. //使用AlarmManger的setRepeating方法设置定期执行的时间间隔（seconds秒）和需要执行的Service
15. manager.setRepeating(AlarmManager.ELAPSED\_REALTIME, triggerAtTime,
16. seconds * 1000, pendingIntent);
17. }
18. //停止轮询服务
19. public static void stopPollingService(Context context, Class&lt;?&gt; cls,String action) {
20. AlarmManager manager = (AlarmManager) context
21. .getSystemService(Context.ALARM\_SERVICE);
22. Intent intent = new Intent(context, cls);
23. intent.setAction(action);
24. PendingIntent pendingIntent = PendingIntent.getService(context, 0,
25. intent, PendingIntent.FLAG\_UPDATE\_CURRENT);
26. //取消正在执行的服务
27. manager.cancel(pendingIntent);
28. }
29. }

 

**二、构建轮询任务执行PollingService.java**

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/9317499 "view plain")[copy](http://blog.csdn.net/tangren03/article/details/9317499 "copy")

01. public class PollingService extends Service {
02. public static final String ACTION = "com.ryantang.service.PollingService";
03. private Notification mNotification;
04. private NotificationManager mManager;
05. @Override
06. public IBinder onBind(Intent intent) {
07. return null;
08. }
09. @Override
10. public void onCreate() {
11. initNotifiManager();
12. }
13. @Override
14. public void onStart(Intent intent, int startId) {
15. new PollingThread().start();
16. }
17. //初始化通知栏配置
18. private void initNotifiManager() {
19. mManager = (NotificationManager) getSystemService(NOTIFICATION\_SERVICE);
20. int icon = R.drawable.ic\_launcher;
21. mNotification = new Notification();
22. mNotification.icon = icon;
23. mNotification.tickerText = "New Message";
24. mNotification.defaults |= Notification.DEFAULT\_SOUND;
25. mNotification.flags = Notification.FLAG\_AUTO\_CANCEL;
26. }
27. //弹出Notification
28. private void showNotification() {
29. mNotification.when = System.currentTimeMillis();
30. //Navigator to the new activity when click the notification title
31. Intent i = new Intent(this, MessageActivity.class);
32. PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
33. Intent.FLAG\_ACTIVITY\_NEW\_TASK);
34. mNotification.setLatestEventInfo(this,
35. getResources().getString(R.string.app\_name), "You have new message!", pendingIntent);
36. mManager.notify(0, mNotification);
37. }
38. /\**
39. * Polling thread
40. * 模拟向Server轮询的异步线程
41. * @Author Ryan
42. * @Create 2013-7-13 上午10:18:34
43. \*/
44. int count = 0;
45. class PollingThread extends Thread {
46. @Override
47. public void run() {
48. System.out.println("Polling...");
49. count ++;
50. //当计数能被5整除时弹出通知
51. if (count % 5 == 0) {
52. showNotification();
53. System.out.println("New message!");
54. }
55. }
56. }
57. @Override
58. public void onDestroy() {
59. super.onDestroy();
60. System.out.println("Service:onDestroy");
61. }
62. }

三、在MainActivity.java中开启和停止PollingService

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/9317499 "view plain")[copy](http://blog.csdn.net/tangren03/article/details/9317499 "copy")

01. public class MainActivity extends Activity {
02. @Override
03. protected void onCreate(Bundle savedInstanceState) {
04. super.onCreate(savedInstanceState);
05. setContentView(R.layout.activity\_main);
06. //Start polling service
07. System.out.println("Start polling service...");
08. PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);
09. }
10. @Override
11. protected void onDestroy() {
12. super.onDestroy();
13. //Stop polling service
14. System.out.println("Stop polling service...");
15. PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
16. }
17. }

 

 

 

**四、运行效果**

运行工程后可以在控制台输出看到，每隔5s就发出一个通知，退出Activity时，轮询服务就停止了，达到了我们事先期望的效果，并且锁屏后很长一段时间也不会停止服务，因为AlarmManager是系统及服务。Demo效果如下图：

![](http://img.blog.csdn.net/20130713113343171?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGFuZ3JlbjAz%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA=%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

 

 

 

在手机上我们可以看到弹出的通知信息，点击通知则进到消息界面：

 

![](http://img.blog.csdn.net/20130713113557906?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGFuZ3JlbjAz%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA=%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)              ![](http://img.blog.csdn.net/20130713113604828?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGFuZ3JlbjAz%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA=%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)              ![](http://img.blog.csdn.net/20130713113610828?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvdGFuZ3JlbjAz%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA=%3D%2Fdissolve%2F70%2Fgravity%2FSouthEast)

 

 

 

当进入消息详情Activity时，顶部状态栏的消息通知就会取消，使用如下方式也可以取消状态栏顶部的消息通知显示：

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/9317499 "view plain")[copy](http://blog.csdn.net/tangren03/article/details/9317499 "copy")

1. NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION\_SERVICE);
2. manager.cancelAll();

以上就实现了使用AlarmManger实现轮询的一种方式，有不足或缺陷的地方欢迎大家留言补充，以上代码只是部分，需要工程源码的同学可以到Github上Clone：[https://github.com/tangren03/RTPollingDemo](https://github.com/tangren03/RTPollingDemo)