Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 定時提醒實作:AlarmManager 結合廣播機制與 Notification

編輯:Android 開發實例

「到點提醒我」這個需求,Android 提供了完整的三件套:用 AlarmManager 排程、用 BroadcastReceiver 接收時間到了的訊號、用 Notification 把訊息送到使用者眼前。本文把這三塊逐一組起來。

一、先理解廣播事件機制

Android 的廣播處理類似一般事件處理,差別在觸發方式:後者靠使用者點擊按鈕這類元件行為,前者則是透過構造 Intent 物件、呼叫 sendBroadcast() 發出系統層級的事件廣播來傳遞資訊。

接收端則是定義一個繼承 BroadcastReceiver 的類別,覆寫它的 onReceive() 方法在其中回應事件。系統內建了許多標準的 Broadcast Action,例如 ACTION_TIME_CHANGED(時間改變時觸發)、BOOT_COMPLETED(開機完成);當然也可以自訂。

二、整體結構

整個功能拆成三塊:

  1. 定時——由 Activity 發出廣播
  2. 接收——由 BroadcastReceiver 攔下廣播
  3. 提醒——由 Notification 呈現給使用者

三、如何定時:AlarmManager

手機的鬧鐘功能背後就是 AlarmManager。它提供一種系統級的排程服務,允許你安排「在某個時間點執行某個服務」。

使用步驟:

  1. 取得 AlarmManager 實例。它一般不直接 new,而是透過 Context.getSystemService(Context.ALARM_SERVICE) 取得。
  2. 定義一個 PendingIntent 用來發出廣播。
  3. 呼叫 AlarmManager 的相關方法設定定時、重複提醒等行為。

ReminderSetting.java:

package com.Reminder;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * 觸發廣播事件並設定鬧鐘
 */
public class ReminderSetting extends Activity {
    Button btnEnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /* 建立一個按鈕,點擊後啟用鬧鐘 */
        btnEnable = (Button) findViewById(R.id.btnEnable);
        btnEnable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setReminder(true);
            }
        });
    }

    /**
     * 設定鬧鐘
     *
     * @param b 是否啟用
     */
    private void setReminder(boolean b) {
        // 取得 AlarmManager 實例
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

        // 建立一個用來發出廣播的 PendingIntent
        PendingIntent pi = PendingIntent.getBroadcast(
                ReminderSetting.this, 0, new Intent(this, MyReceiver.class), 0);

        if (b) {
            // 這裡直接用目前時間作為鬧鐘時間
            Calendar c = Calendar.getInstance();
            // 排設定時
            am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
        } else {
            // 取消目前排程
            am.cancel(pi);
        }
    }
}

這裡有兩個細節值得說明。

為什麼用 PendingIntent 而非直接 startActivity?因為 AlarmManager 觸發的時間點不在你的應用行程內,它需要一個「授權憑證」,在未來那個時刻代你的應用執行廣播。PendingIntent 就是這個憑證。

RTC_WAKEUP 的意義。RTC_WAKEUP 表示鬧鐘時間到時會喚醒裝置(螢幕會亮)。若改成 RTC,裝置休眠時提醒就會被延後到裝置醒來才處理。做提醒功能通常要用 WAKEUP 版本,但這也意味著比較耗電,實務上會搭配精確度權限(SCHEDULE_EXACT_ALARM)與使用者可關閉的設定項。

四、接收廣播

新建一個類別繼承 BroadcastReceiver 並實作 onReceive()。廣播送達時,系統就會呼叫這個方法,所以我們在其中加上「跳到提醒畫面」的程式碼。

MyReceiver.java:

package com.Reminder;

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

/**
 * 接收廣播並啟動顯示提醒的 Activity
 */
public class MyReceiver extends BroadcastReceiver {
    /**
     * 接收到廣播時呼叫
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        /* 啟動 MyAlarm 顯示提醒 */
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, MyAlarm.class);
        context.startActivity(intent);
    }
}

這裡有個實作上的問題要指出:FLAG_ACTIVITY_NEW_TASK 只解決了「從非 Activity 環境啟動 Activity 需要新 task」的技術問題,但並不保證使用者真的會看到——如果裝置正在使用其他應用,這個提醒畫面可能被蓋住,甚至在新版 Android 上被背景啟動限制攔下。更可靠的做法是:在 onReceive 裡直接發出一則 Notification,點擊後才開啟 MyAlarm。這樣做既符合系統的背景執行政策,也不會打斷使用者正在做的事。

別忘了在 AndroidManifest.xml 註冊:

<receiver android:name=".MyReceiver">
    <intent-filter>
        <action android:name="com.Reminder.MyReceiver" />
    </intent-filter>
</receiver>

五、提醒功能

新建一個 Activity,在其中透過 Notification 物件提醒使用者,並加上提示音、顯示內容的 TextView,以及一個取消提醒的按鈕。

建立 Notification 的步驟:

  1. 取得系統服務 NotificationManager,透過 Context.getSystemService(NOTIFICATION_SERVICE)。
  2. 實例化 Notification 物件並設定所需屬性,例如聲音。
  3. 呼叫 NotificationManager 的 notify() 顯示通知。

MyAlarm.java:

package com.Reminder;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * 顯示提醒資訊
 */
public class MyAlarm extends Activity {
    /** 應用內唯一的通知識別碼 */
    public static final int NOTIFICATION_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_alarm);

        // 取得 NotificationManager 實例
        final NotificationManager nm =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        // 建立 Notification 物件
        Notification n = new Notification();

        /* 設定提示音,有兩種方式 */
        // n.sound = Uri.parse("file:///sdcard/alarm.mp3");
        n.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");

        // 發出通知
        nm.notify(NOTIFICATION_ID, n);

        /* 顯示提示內容 */
        TextView tv = (TextView) findViewById(R.id.tvNotification);
        tv.setText("Hello, it's time to bla bla...");

        /* 取消提醒的按鈕 */
        Button btnCancel = (Button) findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                nm.cancel(NOTIFICATION_ID);
                finish();
            }
        });
    }
}

這段程式碼展示了 Notification 的最小構成,但要提醒的是它反映的是舊版 API。目前的實作必須補上:

  • NotificationChannel:API 26 起未建立 channel 的通知完全不會顯示,這是最常見的「程式沒報錯但通知不出來」原因。
  • setSmallIcon():新版系統必填,缺少會靜默失敗。
  • POST_NOTIFICATIONS 權限:API 33 起需執行時向使用者詢問。
  • 設定 PendingIntent:點擊通知後該做什麼,需透過 setContentIntent() 指定。

最後一個實務建議:提醒類應用通常需要處理「重複排程」與「使用者關掉提醒」兩件事。重複可以改用 setRepeating() 或 WorkManager(視精度需求而定);關閉提醒則務必在設定畫面提供開關,並在關閉時呼叫 am.cancel(pi) 把已排的鬧鐘清掉,否則使用者關了設定卻還是會收到通知,體驗很差。

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