AlarmManager是Android中的一種係統級別的提醒服務,它會為我們在特定的時刻廣播一個指定的Intent。而使用Intent的時候,我們還需要它執行一個動作,如startActivity,startService,startBroadcast,才能使Intent有用。通常我們使用PendingIntent,它可以理解為對Intent的封裝,包含了指定的動作。
AlarmManager 包含的主要方法:
<span style="font-size:14px;">// 取消已經注冊的與參數匹配的定時器
void cancel(PendingIntent operation)
//注冊一個新的延遲定時器
void set(int type, long triggerAtTime, PendingIntent operation)
//注冊一個重複類型的定時器
void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)
//注冊一個非精密的重複類型定時器
void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
//設置時區
void setTimeZone(String timeZone) </span>
定時器主要類型:
public static final int ELAPSED_REALTIME
// 當係統進入睡眠狀態時,這種類型的鬧鈴不會喚醒係統。直到係統下次被喚醒才傳遞它,該鬧鈴所用的時間是相對時間,是從係統啟動後開始計時的,包括睡眠時 間,可以通過調用SystemClock.elapsedRealtime()獲得。係統值是3 (0x00000003)。
public static final int ELAPSED_REALTIME_WAKEUP
//能喚醒係統,用法同ELAPSED_REALTIME,係統值是2 (0x00000002) 。
public static final int RTC
//當係統進入睡眠狀態時,這種類型的鬧鈴不會喚醒係統。直到係統下次被喚醒才傳遞它,該鬧鈴所用的時間是絕對時間,所用時間是UTC時間,可以通過調用 System.currentTimeMillis()獲得。係統值是1 (0x00000001) 。
public static final int RTC_WAKEUP
//能喚醒係統,用法同RTC類型,係統值為 0 (0x00000000) 。
Public static final int POWER_OFF_WAKEUP
//能喚醒係統,它是一種關機鬧鈴,就是說設備在關機狀態下也可以喚醒係統,所以我們把它稱之為關機鬧鈴。使用方法同RTC類型,係統值為4(0x00000004)。
當你的應用不在運行,而此時你仍然需要你的應用去執行一些操作(比如,短信攔截),隻有這種時候才使用AlarmManager, 其他正常情況下的,推薦使用Handler。
AlarmManager 生命周期:
repeating AlarmManager一旦啟動就會一直在後台運行(除非執行cancel方法),可以在“應用管理”中看到這個應用狀態是正在運行。 “強行停止”可以讓Alarmmanager停掉。
嚐試了幾種任務管理器, 都隻能重置計數器(確實釋放內存了),但都無法關閉定時器,隻有係統自帶的“強行停止”奏效。
如果某個AlarmManager已經啟動, 程序又再次去啟動它,隻要PendingIntent是一樣,那麼之前那個AlarmManager會被release掉。
如何使用AlarmManager?
使用AlarmManager共有三種方式, 都是通過PendingIntent。
getActivity(Context, int, Intent, int)
getBroadcast(Context, int, Intent, int)
getService(Context, int, Intent, int)
使用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對象中常用的方法有三個:
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()方法。
這邊就舉一個使用BroadCast的例子。
首先是創建一個BroadCast類,需要繼承BroadCastReceiver, 如下:
/*
* Copyright (c) 2011, Yulong Information Technologies
* All rights reserved.
*
* @Project: AlarmTest
* @author: Robot
*/
package com.yfz;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* @author Robot
* @weibo http://weibo.com/feng88724
* @date Nov 18, 2011
*/
public class ActionBroadCast extends BroadcastReceiver {
private static int num = 0;
/* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("ActionBroadCast", "New Message !" + num++);
}
}
下麵就讓我們啟動AlarmManager, 這邊就直接在Activity中啟動了, 如下:
package com.yfz;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class AlarmTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(this, ActionBroadCast.class), Intent.FLAG_ACTIVITY_NEW_TASK);
long now = System.currentTimeMillis();
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi);
}
}
這邊用Repeating的方式。 每隔3秒發一條廣播消息過去。RTC_WAKEUP的方式,保證即使手機休眠了,也依然會發廣播消息。
最後看一下AndroidManifest文件,主要是注冊一下Activity和BroadCast。 (實際使用中最好再加個filter,自己定義一個Action比較好)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yfz"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".AlarmTestActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="ActionBroadCast">
</receiver>
</application>
</manifest>
Service的其實也差不多,隻要在OnStart()方法中寫需要執行的操作即可。