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

Android 隨筆:鬧鐘背後的關鍵——AlarmManager 詳解

編輯:關於 Android 程式設計

一、AlarmManager 是什麼

要做一個鬧鐘應用,最關鍵的角色莫過於 AlarmManager。它被稱為全局定時器,顧名思義就是「鬧鐘管理」,是 Android 中相當典型的系統級提示服務:在指定時刻為你送出一個指定的 Intent。

換句話說,我們設定一個時間,時間一到,AlarmManager 就幫我們廣播那個 Intent。實作上通常搭配 PendingIntent 使用——它相當於 Intent 的包裝,在 Intent 之上再附加一個「指定動作」。平時使用 Intent 時,還得自行呼叫 startActivity、startService 或 sendBroadcast 才有意義;而 PendingIntent 已經把這個動作包進去了。

// 定義一個 PendingIntent 物件
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

二、常用方法

set(int type, long triggerAtMillis, PendingIntent operation)
設定一次性鬧鐘。第二個參數是觸發等待的時間,含義與 type 相關;第三個參數是鬧鐘響應的動作。

type 的幾種取值:

· AlarmManager.ELAPSED_REALTIME:手機休眠時鬧鐘不可用,採相對時間(相對於開機起算),狀態值為 3。

· AlarmManager.ELAPSED_REALTIME_WAKEUP:休眠時會喚醒系統並執行提示,同樣使用相對時間,狀態值為 2。

· AlarmManager.RTC:休眠時不可用,採絕對時間(當前系統時間),狀態值為 1。

· AlarmManager.RTC_WAKEUP:休眠時會喚醒系統並提示,採絕對時間,狀態值為 0。

· AlarmManager.POWER_OFF_WAKEUP:手機關機狀態下仍能提示,採絕對時間,狀態值為 4。不過我實測時並未找到這個常量,推測與 SDK 版本有關。

setExact(...):在指定時間精確觸發,執行精度相對較高。

setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)
設定重複鬧鐘,第三個參數是兩次執行之間的間隔。

setInexactRepeating(...):重複鬧鐘的不精確版本,相對節能,因為系統可能把幾個時間相近的鬧鐘合併執行,以減少裝置喚醒次數。intervalMillis 可使用 INTERVAL_FIFTEEN_MINUTES、INTERVAL_HALF_HOUR、INTERVAL_HOUR、INTERVAL_HALF_DAY、INTERVAL_DAY 等預設常量。

cancel(PendingIntent operation):取消鬧鐘,移除任何意圖相符的鬧鐘。

setTimeZone(String timeZone):設定系統預設時區,需要 android.permission.SET_TIME_ZONE 權限。

三、一個最小可用的鬧鐘範例

首先在 AndroidManifest.xml 註冊廣播接收器:

<receiver android:name=".AlarmReceiver">
    <!-- 若採內部類靜態註冊,名稱前請加上 $ -->
    <intent-filter>
        <action android:name="android.intent.action.ALARM_RECEIVER" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

接著撰寫廣播接收器,接收鬧鐘事件並做處理:

package com.example.alarmmanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // 此處可加入鬧鐘鈴聲
        Toast.makeText(arg0, "我是鬧鐘,我要叫醒你...", Toast.LENGTH_SHORT).show();
    }
}

最後在 MainActivity 中串起來:

public class MainActivity extends Activity implements OnClickListener {

    private AlarmManager alarmManager;
    private PendingIntent operation;

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

        findViewById(R.id.clock).setOnClickListener(this);
        findViewById(R.id.repeating_clock).setOnClickListener(this);
        findViewById(R.id.cancel_clock).setOnClickListener(this);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        Intent intent = new Intent("android.intent.action.ALARM_RECEIVER");
        operation = PendingIntent.getBroadcast(this, 0, intent, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clock:            // 一次性鬧鐘
                alarmManager.set(AlarmManager.RTC_WAKEUP, 10000, operation);
                break;
            case R.id.repeating_clock:  // 重複鬧鐘
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 10000, operation);
                break;
            case R.id.cancel_clock:     // 取消鬧鐘
                alarmManager.cancel(operation);
                break;
            default:
                break;
        }
    }
}

版面配置只要擺三顆按鈕即可:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="設置一次性鬧鐘" />

    <Button
        android:id="@+id/repeating_clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="設置重復鬧鐘" />

    <Button
        android:id="@+id/cancel_clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="取消鬧鐘" />
</LinearLayout>

補充一點實務經驗:AlarmManager 的時間精度會受 Doze 模式與各家 ROM 的省電策略影響,若要求「準點」,Android 5.1 以後應改用 setExactAndAllowWhileIdle()。另外 PendingIntent 若未加上唯一 requestCode 或明確的 Intent 過濾,取消時容易誤刪其他鬧鐘,這點在設計時要多留意。

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