AlarmManager 系統服務的開發精要

使用目的

目的: 簡單一句話就是它可以發送一個PendingIntent出來.
使用AlarmManager可以實現定時發送一個PendingIntent出來, 如果這個PendingInteng封裝的是一個廣播類型的intent對象, 那么就可以讓監聽這個廣播類型的BroadcastReceiver的onReceive() 定時被執行某些特定的操作.

典型應用場景是, 在天氣app的開發中, 定時更新天氣數據(從網上拉取數據, 并解析數據, 把結果存入數據庫的操作)的功能就是利用AlarmManager來完成的.

代碼

AlarmManager 是一個系統級的服務, 獲取這個服務的方法是:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

使用它的目的就是通過調用它的API( eg. setRepeating() ), 定時向系統發送一個PendingIntent對象出來.

PendingIntent本質上來說, 就是對intent的一個包裝, 如果這個PendingIntent對象是通過PendingIntent.getBroadcast()獲取到的, 那么當PendingIntent對象發送出來后, 系統會自動調用sendBroadcast(intent), 發送它里面封裝的intent廣播對象. 這個廣播對象所對應的BroadcastReceiver的onReceive()方法就會被定期的執行.

public class AutoUpdateService extends Service {
    public static final String ACTION_BACKGROUND_UPDATE = "com.hola.weather.action_background_update";

    @Override
    public void onCreate() {
        super.onCreate();

        BackgroundUpdateReceiver backgroundUpdateReceiver = new BackgroundUpdateReceiver();
        registerReceiver(backgroundUpdateReceiver, new IntentFilter(ACTION_BACKGROUND_UPDATE));

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(ACTION_BACKGROUND_UPDATE);
        pendingIntent = PendingIntent.getBroadcast(AutoUpdateService.this, 0, intent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + getCurrentUpdateInterval(), getCurrentUpdateInterval(), pendingIntent);
    // API: setRepeating(int type,long startTime,long intervalTime,PendingIntent pendingIntent);

    }

    private class BackgroundUpdateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
        //執行從網上拉取數據, 并解析數據, 把結果存入數據庫的操作
    }
    }

}

refer to:
http://blog.csdn.net/wangxingwu_314/article/details/8060312

---DONE.------

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容