Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 AlarmManager + Service 打造 Android 不間斷輪詢服務

編輯:關於 Android 程式設計

消息獲取到底該用輪詢還是推送,取決於實際業務形態。如果對即時性要求高,比如微博新通知、突發新聞,那推送才是正解。但若只是普通的狀態檢測,例如每半小時或一小時檢查一次更新,輪詢其實是個很不錯的選擇——不必額外架設推送伺服器,也不用配置推送服務。

而且推送通常靠維持長連線來實作,在手機端也是要耗電的。本文要介紹的就是 Android 上實作輪詢機制最合適的工具:AlarmManager。

為什麼不用 Timer 或 Service 迴圈?

AlarmManager 主要用來定時或週期性地觸發某個事件,系統的鬧鐘應用就是靠它實作的,我們要用的正是它的週期執行能力。

週期任務固然可以用 Timer 和 TimerTask 實作,也可以開一個 Service 在 Thread 裡跑 while 迴圈。但最佳方案仍是 AlarmManager,原因在於 Android 的系統鎖(wakelock)機制:當系統偵測到設備閒置一段時間後,會關閉部分非必要的服務以節省資源與電力。若用 Timer 或 Service 實作,很可能螢幕熄滅一段時間後服務就被停掉,輪詢自然也跟著停擺。這一點非常容易驗證。

接下來就用 AlarmManager + Service + Thread 組出完整的輪詢服務。

一、輪詢工具類 PollingUtils

public class PollingUtils {

    // 開啟輪詢服務
    public static void startPollingService(Context context, int seconds,
                                           Class<?> cls, String action) {
        // 獲取 AlarmManager 系統服務
        AlarmManager manager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);

        // 包裝需要執行 Service 的 Intent
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(
                context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        // 觸發服務的起始時間
        long triggerAtTime = SystemClock.elapsedRealtime();

        // 使用 setRepeating 設置定期執行的時間間隔(seconds 秒)和需要執行的 Service
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME,
                triggerAtTime, seconds * 1000, pendingIntent);
    }

    // 停止輪詢服務
    public static void stopPollingService(Context context, Class<?> cls, String action) {
        AlarmManager manager = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(
                context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        // 取消正在執行的服務
        manager.cancel(pendingIntent);
    }
}

二、輪詢服務 PollingService

public class PollingService extends Service {

    public static final String ACTION = "com.ryantang.service.PollingService";

    private Notification mNotification;
    private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        initNotifiManager();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        new PollingThread().start();
    }

    // 初始化通知欄配置
    private void initNotifiManager() {
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        mNotification = new Notification();
        mNotification.icon = icon;
        mNotification.tickerText = "New Message";
        mNotification.defaults |= Notification.DEFAULT_SOUND;
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    }

    // 彈出 Notification
    private void showNotification() {
        mNotification.when = System.currentTimeMillis();
        // 點擊通知標題後跳轉到新 Activity
        Intent i = new Intent(this, MessageActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
        mNotification.setLatestEventInfo(this,
                getResources().getString(R.string.app_name),
                "You have new message!", pendingIntent);
        mManager.notify(0, mNotification);
    }

    /**
     * 模擬向 Server 輪詢的異步線程
     */
    int count = 0;

    class PollingThread extends Thread {
        @Override
        public void run() {
            System.out.println("Polling...");
            count++;
            // 當計數能被 5 整除時彈出通知
            if (count % 5 == 0) {
                showNotification();
                System.out.println("New message!");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service:onDestroy");
    }
}

三、在 Activity 中啟停

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 啟動輪詢服務
        System.out.println("Start polling service...");
        PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止輪詢服務
        System.out.println("Stop polling service...");
        PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);
    }
}

幾點實務補充

把輪詢掛在 Activity 的 onDestroy 裡取消,只適合演示用途;正式專案中通常會希望輪詢在應用退到背景後仍然持續,這時應把啟動與停止的時機交由更長生命週期的元件(例如開機廣播接收器或 JobScheduler / WorkManager)來管理。另外,從 Android 4.4 起 setRepeating 的精度會被系統刻意降低以達到電力最佳化,若對時間精度有要求,需要改用 setExact 系列 API 並搭配 AlarmManager.setExactAndAllowWhileIdle。最後别忘了在清單檔註冊 Service。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved