1. 程式人生 > >AlarmManager鬧鐘定時操作

AlarmManager鬧鐘定時操作

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);
該方法也用於設定重複鬧鐘,與第二個方法相似,不過其兩個鬧鐘執行的間隔時間不是固定的而已。鬧鐘的型別,常用的有5個值:AlarmManager.ELAPSED_REALTIME、 AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、 AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP。AlarmManager.ELAPSED_REALTIME表示鬧鐘在手機睡眠狀態下不可用,該狀態下鬧鐘使用相對時間(相對於系統啟動開始),狀態值為3;AlarmManager.ELAPSED_REALTIME_WAKEUP表示鬧鐘在睡眠狀態下會喚醒系統並執行提示功能,該狀態下鬧鐘也使用相對時間,狀態值為2;
AlarmManager.RTC表示鬧鐘在睡眠狀態下不可用,該狀態下鬧鐘使用絕對時間,即當前系統時間,狀態值為1;AlarmManager.RTC_WAKEUP表示鬧鐘在睡眠狀態下會喚醒系統並執行提示功能,該狀態下鬧鐘使用絕對時間,狀態值為0;

AlarmManager.POWER_OFF_WAKEUP表示鬧鐘在手機關機狀態下也能正常進行提示功能,所以是5個狀態中用的最多的狀態之一,該狀態下鬧鐘也是用絕對時間,狀態值為4;不過本狀態好像受SDK版本影響,某些版本並不支援;

使用方法:

只介紹靜態廣播方法

一 、使用、設定

//建立Intent物件,action為ELITOR_CLOCK,附加資訊為字串“鬧鐘時間到”
        Intent intent = new Intent("ELITOR_CLOCK");
        intent.putExtra("msg","鬧鐘時間到");

//定義一個PendingIntent物件,PendingIntent.getBroadcast包含了sendBroadcast的動作。
//也就是傳送了action 為"ELITOR_CLOCK"的intent
        PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);

//AlarmManager物件,注意這裡並不是new一個物件,Alarmmanager為系統級服務
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

//設定鬧鐘從當前時間開始,每隔5s執行一次PendingIntent物件pi,注意第一個引數與第二個引數的關係
// 5秒後通過PendingIntent pi物件傳送廣播
        am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),5*1000,pi);

二、MyReceiver  extends BroadcastReceiver

public class MyReceiver  extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent)
    {
        // TODO Auto-generated method stub
        Log.d("MyTag", "到來......................");
        String msg = intent.getStringExtra("msg");
        Toast.makeText(context,msg,Toast.LENGTH_SHORT).show();
    }

}

三、註冊靜態廣播

<receiver android:name=".MyReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ALARM_RECEIVER" /><!-- 廣播接收的Intent -->
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="ELITOR_CLOCK" />
            </intent-filter>
        </receiver>