編輯:Android 開發實例
「到點提醒我」這個需求,Android 提供了完整的三件套:用 AlarmManager 排程、用 BroadcastReceiver 接收時間到了的訊號、用 Notification 把訊息送到使用者眼前。本文把這三塊逐一組起來。
Android 的廣播處理類似一般事件處理,差別在觸發方式:後者靠使用者點擊按鈕這類元件行為,前者則是透過構造 Intent 物件、呼叫 sendBroadcast() 發出系統層級的事件廣播來傳遞資訊。
接收端則是定義一個繼承 BroadcastReceiver 的類別,覆寫它的 onReceive() 方法在其中回應事件。系統內建了許多標準的 Broadcast Action,例如 ACTION_TIME_CHANGED(時間改變時觸發)、BOOT_COMPLETED(開機完成);當然也可以自訂。
整個功能拆成三塊:
手機的鬧鐘功能背後就是 AlarmManager。它提供一種系統級的排程服務,允許你安排「在某個時間點執行某個服務」。
使用步驟:
Context.getSystemService(Context.ALARM_SERVICE) 取得。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 的步驟:
Context.getSystemService(NOTIFICATION_SERVICE)。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。目前的實作必須補上:
setContentIntent() 指定。最後一個實務建議:提醒類應用通常需要處理「重複排程」與「使用者關掉提醒」兩件事。重複可以改用 setRepeating() 或 WorkManager(視精度需求而定);關閉提醒則務必在設定畫面提供開關,並在關閉時呼叫 am.cancel(pi) 把已排的鬧鐘清掉,否則使用者關了設定卻還是會收到通知,體驗很差。
Android JSON 解析入門:用 JSONObject 撈出你要的那幾個欄位
JSON(JavaScript Object Notation)自從被提出之後,因為格式輕量、可讀性高,很快就在 Web API 的世界裡取代了 XML 的位置。不管是瀏
ExpandableListView 實作三層樹形菜單的兩個關鍵難題
Android 上做樹形菜單,標準武器是 ExpandableListView,也有人自己繼承 ListView 或 LinearLayout 硬刻。但 Expandab
Android 進階:藍牙傳感應用實例
前文介紹過 Android 利用麥克風采集並顯示模擬信號的方法,這種方式適用於沒有 IO 控制、單純讀取信號的場景。但如果傳感器本身還需要控制電路(例如採集血氧信號時要紅
Android 二級下拉菜單與實時搜索聯動的實現方法
需求很常見:頁面上方一個搜索框,下方一個兩級菜單;有輸入時展示搜索結果列表,清空輸入後恢復菜單。本文用 ExpandableListView + ListView 的顯示