AlarmManager是Android中的一種系統級別的提醒服務,它會為我們在特定的時刻廣播一個指定的Intent。而使用Intent的時候,我們還需要它執行一個動作,如startActivity,startService,startBroadcast,才能使Intent有用。通常我們使用PendingIntent,它可以理解為對Intent的封裝,包含了指定的動作。
我們可以通過PendingIntent的靜態方法得到一個PendingIntent對象,如下:
- PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
使用PendingIntent的getBroadcast (Context context, int requestCode, Intent intent, int flags)方法可以得到一個發送廣播動作的PendingIntent對象。其中getBroadcast的第4個參數可以為以下4個常量或其他支持使用Intent.fillIn()來控制它的變量:
FLAG_CANCEL_CURRENT:如果描述的PendingIntent對象已經存在時,會先取消當前的PendingIntent對象再生成新的。
FLAG_NO_CREATE:如果描述的PendingIntent對象不存在,它會返回null而不是去創建它。
FLAG_ONE_SHOT:創建的PendingIntent對象只使用一次。
FLAG_UPDATE_CURRENT:如果描述的PendingIntent對象存在,則保留它,並將新的PendingIntent對象的數據替換進去。
接下來看AlarmManager,我們通過以下代碼來取得AlarmManager對象。
- AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
AlarmManager對象中常用的方法有三個:
1、set(int type,long startTime,PendingIntent pi),用於設置一次鬧鍾。
2、setRepeating(int type,long startTime,long intervalTime,PendingIntent pi),用於設置重復鬧鍾。
3、setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi),同樣是用於設置重復鬧鍾,但是它是不准確的,相對於第二個方法,也更加節能。因為系統會將差不多的鬧鍾進行合並,以避免在不必要地喚醒設備。
在上面的三個方法中,type為鬧鍾的類型,它可以使用以下四個常量:
ELAPSED_REALTIME:鬧鍾在睡眠狀態下不可用,使用的是相對系統啟動時間。
ELAPSED_REALTIME_WAKEUP:鬧鍾在睡眠狀態下可用,使用的是相對系統啟動時間。
RTC:鬧鍾在睡眠狀態下不可用,使用的是真實時間。
RTC_WAKEUP:鬧鍾在睡眠狀態下可用,使用的是真實時間。
startTime為鬧鍾開始時間。
intervalTime為鬧鍾間隔,在第三個方法中,內置的幾個變量如下:
INTERVAL_FIFTEEN_MINUTES
INTERVAL_HALF_HOUR
INTERVAL_HOUR
INTERVAL_HALF_DAY
INTERVAL_DAY
如果我們設定的是發送廣播的鬧鍾,我們還需要寫一個廣播接收器,並對其進行注冊,它才會在鬧鍾開始的時候接收到廣播。
如果要設定啟動Activity或Service的鬧鍾,則在創建PendingIntent的時候,首先Intent對象需設定指定的Activity或Service的class對象,然后對應的調用PendingIntent.getActivity()或PendingIntent.getService()方法。
下面以設置發送廣播的鬧鍾代碼實例來看AlarmManager的使用:
首先設定一個鬧鍾:
- Intent intent = new Intent("pw.msdx.ACTION_SEND");
- PendingIntent sendIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
- am.cancel(sendIntent);
- am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60 * 10 * 1000, sendIntent);
在上面的例子中,就會從當前的時間開始,每10分鍾啟動一次鬧鍾提醒。需要注意的是,如果設定的開始時間已經過去,它會馬上啟動鬧鍾提醒。
接下來需要寫一個廣播接收器來接收這個廣播並進行處理。
代碼如下:
- public class SendReceiver extends BroadcastReceiver {
- public final static String ACTION_SEND = "pw.msdx.ACTION_SEND<span style="font-family: Arial, Helvetica, sans-serif;">";</span>
- @Override
- public void onReceive(final Context context, Intent intent) {
- String action = intent.getAction();
- if (ACTION_SEND.equals(action)) {
- Log.i("SendReceiver", "send a message");
- }
- }
- }
然后我們還需要注冊這個廣播接收器,這樣它才能接收到廣播。這里采用的是靜態注冊的方法,在AndroidManifest里進行注冊:
- <receiver
- android:name=".SendReceiver"
- android:enabled="true"
- android:exported="true"
- >
- <intent-filter>
- <action android:name="pw.msdx.ACTION_SEND"/>
- </intent-filter>
- </receiver>
