天天看點

Android AlarmManager實作不間斷輪詢服務

在消息的擷取上是選擇輪詢還是推送得根據實際的業務需要來技術選型,例如對消息實時性比較高的需求,比如微網誌新通知或新聞等那就最好是用推送了。但如果隻是一般的消息檢測比如更新檢查,可能是半個小時或一個小時一次,那用輪詢也是一個不錯的選擇,因為不需要額外搭建推送伺服器,不用額外配置推送服務。另外推送現在一般以維持長連接配接的方式實作,在手機用戶端也會耗費一定的電量。今天就介紹一個在Android上實作輪詢機制的方法——使用AlarmManager

AlarmManager在Android中主要用來定時處理一個事件或是定期處理一個事件,比如鬧鐘應用就是使用AlarmManager來實作的,我們今天要使用AlarmManager的定期執行功能來實作輪詢的功能。對于定期執行任務也可以用Timer和TimerTask來實作,也可以開一個Service在Thread裡面以while循環來實作。但最好的方案還是選用AlarmManager,這裡涉及一個Android系統鎖的機制,即系統在檢測到一段時間沒有活躍以後,會關閉一些不必要的服務來減少資源和電量消耗。使用Timer和Service來實作的話很可能出現的情況就是螢幕熄滅後一段時間,服務就被停止了,當然輪詢也就被停止了。這個大家可以實驗一下,之前我寫過一篇文章也介紹了一種保持背景喚醒的機制《使用WakeLock使Android應用程式保持背景喚醒》,感興趣的可以看看。那麼接下來就開始使用AlarmManager+Service+Thread來實作我們的輪詢服務吧!

一、建立輪詢工具類PollingUtils.java

[java]view plaincopy

  1. publicclass PollingUtils {  
  2. //開啟輪詢服務
  3. publicstaticvoid startPollingService(Context context, int seconds, Class<?> cls,String action) {  
  4. //擷取AlarmManager系統服務
  5.        AlarmManager manager = (AlarmManager) context  
  6.                .getSystemService(Context.ALARM_SERVICE);  
  7. //包裝需要執行Service的Intent
  8.        Intent intent = new Intent(context, cls);  
  9.        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. publicstaticvoid stopPollingService(Context context, Class<?> cls,String action) {  
  20. //取消正在執行的服務
  21.        manager.cancel(pendingIntent);  
  22. }  

二、建構輪詢任務執行PollingService.java

  1. publicclass PollingService extends Service {  
  2. publicstaticfinal String ACTION = "com.ryantang.service.PollingService";  
  3. private Notification mNotification;  
  4. private NotificationManager mManager;  
  5. @Override
  6. public IBinder onBind(Intent intent) {  
  7. returnnull;  
  8. publicvoid onCreate() {  
  9.        initNotifiManager();  
  10. publicvoid onStart(Intent intent, int startId) {  
  11. new PollingThread().start();  
  12. //初始化通知欄配置
  13. privatevoid initNotifiManager() {  
  14.        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  15. int icon = R.drawable.ic_launcher;  
  16.        mNotification = new Notification();  
  17.        mNotification.icon = icon;  
  18.        mNotification.tickerText = "New Message";  
  19.        mNotification.defaults |= Notification.DEFAULT_SOUND;  
  20.        mNotification.flags = Notification.FLAG_AUTO_CANCEL;  
  21. //彈出Notification
  22. privatevoid showNotification() {  
  23.        mNotification.when = System.currentTimeMillis();  
  24. //Navigator to the new activity when click the notification title
  25.        Intent i = new Intent(this, MessageActivity.class);  
  26.        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,  
  27.                Intent.FLAG_ACTIVITY_NEW_TASK);  
  28.        mNotification.setLatestEventInfo(this,  
  29.                getResources().getString(R.string.app_name), "You have new message!", pendingIntent);  
  30.        mManager.notify(0, mNotification);  
  31. /**
  32.     * Polling thread
  33.     * 模拟向Server輪詢的異步線程
  34.     * @Author Ryan
  35.     * @Create 2013-7-13 上午10:18:34
  36.     */
  37. int count = 0;  
  38. class PollingThread extends Thread {  
  39. publicvoid run() {  
  40.            System.out.println("Polling...");  
  41.            count ++;  
  42. //當計數能被5整除時彈出通知
  43. if (count % 5 == 0) {  
  44.                showNotification();  
  45.                System.out.println("New message!");  
  46.            }  
  47.        }  
  48. publicvoid onDestroy() {  
  49. super.onDestroy();  
  50.        System.out.println("Service:onDestroy");  

三、在MainActivity.java中開啟和停止PollingService

  1. publicclass MainActivity extends Activity {  
  2. protectedvoid onCreate(Bundle savedInstanceState) {  
  3. super.onCreate(savedInstanceState);  
  4.        setContentView(R.layout.activity_main);  
  5. //Start polling service
  6.        System.out.println("Start polling service...");  
  7.        PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);  
  8. protectedvoid onDestroy() {  
  9. //Stop polling service
  10.        System.out.println("Stop polling service...");  
  11.        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);  

四、運作效果

運作工程後可以在控制台輸出看到,每隔5s就發出一個通知,退出Activity時,輪詢服務就停止了,達到了我們事先期望的效果,并且鎖屏後很長一段時間也不會停止服務,因為AlarmManager是系統及服務。Demo效果如下圖:

Android AlarmManager實作不間斷輪詢服務

在手機上我們可以看到彈出的通知資訊,點選通知則進到消息界面:

Android AlarmManager實作不間斷輪詢服務
Android AlarmManager實作不間斷輪詢服務
Android AlarmManager實作不間斷輪詢服務

當進入消息詳情Activity時,頂部狀态欄的消息通知就會取消,使用如下方式也可以取消狀态欄頂部的消息通知顯示:

以上就實作了使用AlarmManger實作輪詢的一種方式,有不足或缺陷的地方歡迎大家留言補充,以上代碼隻是部分,需要工程源碼的同學可以到Github上Clone:https://github.com/tangren03/RTPollingDemo