編輯:關於 Android 程式設計
要做一個鬧鐘應用,最關鍵的角色莫過於 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 過濾,取消時容易誤刪其他鬧鐘,這點在設計時要多留意。
Android UI 布局技巧:重複背景與 layer-list 圖片組合
在 Android UI 開發中,除了常規的布局標籤,Drawable 資源還有許多實用技巧。本文介紹兩個常見場景:設定重複平鋪背景,以及用 layer-list 組合多
自訂 ActionProvider:在 Toolbar Menu 上做出一顆小紅點
今天的目標有三個: 自訂 ActionProvider。 客製 Toolbar/ActionBar 的 Menu。 在 Toolbar 右側的 Menu 按鈕上加上角標
Android 開發核心知識:Activity 生命週期全解析
啟動或結束一個 Activity,都離不開它的生命週期。Android 開發者依據生命週期中各回呼方法的觸發時機處理對應的業務邏輯,以保證用戶與頁面之間能正常、良好地交互
自訂 Android 自動完成控制項:SocialTokenAutoComplete,讓 @某人 更貼心
在社群類應用中,「@某人」是很常見的互動方式。若使用原生控制項,往往難以兼顧「輸入 @ 後自動提示、選取後以特殊樣式標記」等需求。SocialTokenAutoCompl