編輯:Android 開發實例
無意間看到 Alarm 這個類別,覺得相當有意思,而且實務上應該很常用,於是查了些資料並親手做了一個 demo。
Alarm 是一種在預定時間觸發 Intent 的獨立機制。它不受應用程式範圍的限制,因此即使在應用關閉之後,仍能觸發事件或動作;搭配 BroadcastReceiver 使用時尤其強大——可以透過它啟動應用或執行動作,而不需要應用處於開啟或活躍狀態。舉例來說,你可以用 Alarm 實作鬧鐘、執行定期網路查詢,或把耗時、有成本的任務安排到「非高峰」時段。
若只是應用生命週期內的定時操作,Handler 搭配 Timer 與 Thread 會是更好的選擇,能讓 Android 更有效地管理系統資源。Android 的 Alarm 在裝置休眠時仍保持活躍,也能設定為喚醒裝置;但要注意,所有 Alarm 在裝置重開機後都會被取消。
Alarm 的操作由 AlarmManager 處理,透過 getSystemService 取得:
AlarmManager alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
建立新 Alarm 時,使用 set 方法並指定 Alarm 類型、觸發時間,以及觸發時要呼叫的 Intent;若設定的時間已過去,它會立即觸發。共有四種類型,你的選擇決定了傳入的時間值代表「特定時刻」還是「時間流逝」:
❑ RTC_WAKEUP:在指定時刻喚醒裝置並觸發 Intent。
❑ RTC:在指定時刻觸發 Intent,但不喚醒裝置。
❑ ELAPSED_REALTIME:自開機後經過指定時間即觸發 Intent,但不喚醒裝置;流逝時間包含裝置休眠的時段。
❑ ELAPSED_REALTIME_WAKEUP:自開機後經過指定時間,若需要則喚醒裝置並觸發 Intent。
透過 TimePickerDialog 讓使用者挑選時間,再用 Calendar 計算觸發時刻,最後以 AlarmManager 設定鬧鐘;取消則是呼叫 am.cancel():
- public class AlarmSettingActivity extends Activity {
- private Button setbutton;
- private Button canclebutton;
- private TextView mTextView;
- private Calendar calendar;
- private AlarmManager am;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //獲得Alarm管理實例
- am = (AlarmManager) getSystemService(ALARM_SERVICE);
- calendar = Calendar.getInstance();
- mTextView = (TextView) findViewById(R.id.textinfo);
- setbutton = (Button) findViewById(R.id.setbutton);
- canclebutton = (Button) findViewById(R.id.canclebutton);
- setbutton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- calendar.setTimeInMillis(System.currentTimeMillis());
- int mHour = calendar.get(Calendar.HOUR_OF_DAY);
- int mMinute = calendar.get(Calendar.MINUTE);
- new TimePickerDialog(AlarmSettingActivity.this,
- new TimePickerDialog.OnTimeSetListener() {
- public void onTimeSet(TimePicker view,
- int hourOfDay, int minute) {
- calendar.setTimeInMillis(System
- .currentTimeMillis());
- calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
- calendar.set(Calendar.MINUTE, minute);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MILLISECOND, 0);
- Intent intent = new Intent(AlarmSettingActivity.this, AlarmBroadCastReceiver.class);
- //這裡可以傳遞消息,譬如提醒信息
- Bundle bundle = new Bundle();
- bundle.putString("info", "該起床啦 ~~~~~");
- bundle.putInt("id", new Random().nextInt(100));
- intent.putExtras(bundle);
- //獲得一個可以掛起的Intent
- PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmSettingActivity.this, 0,intent, 0);
- /* 設置鬧鐘 */
- am.set(AlarmManager.RTC_WAKEUP, calendar
- .getTimeInMillis(), pendingIntent);
- /* 設置周期鬧 */
- am.setRepeating(AlarmManager.RTC_WAKEUP, System
- .currentTimeMillis()
- + (10 * 1000), (24 * 60 * 60 * 1000),
- pendingIntent);
- String tmpS = "設置鬧鐘時間為" + format(hourOfDay)
- + ":" + format(minute);
- mTextView.setText(tmpS);
- }
- }, mHour, mMinute, true).show();
- }
- });
- canclebutton.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- Intent intent = new Intent(AlarmSettingActivity.this, AlarmBroadCastReceiver.class);
- PendingIntent pendingIntent = PendingIntent.getBroadcast(
- AlarmSettingActivity.this, 0, intent, 0);
- //取消該Intent
- am.cancel(pendingIntent);
- mTextView.setText("鬧鐘已取消!");
- }
- });
- }
- //格式化字符串 不滿兩位 前面補0
- private String format(int x) {
- String s = "" + x;
- if (s.length() == 1)
- s = "0" + s;
- return s;
- }
- }
這裡用到了 PendingIntent。顧名思義,pending 就是「掛起」的意思,它的功能與 Intent 類似,內部同樣持有 Intent 的引用,主要差別在生命週期:由於 Alarm 不依賴應用,而 Intent 依賴應用,因此改用 PendingIntent——它的生命週期由系統管理,即使建立它的應用被關閉,仍能存在並在別的行程中使用。
鬧鐘觸發時,透過 BroadcastReceiver 接收訊息,再以 Notification 在狀態列顯示提示:
- public class AlarmBroadCastReceiver extends BroadcastReceiver{
- private int id;
- @Override
- public void onReceive(Context context, Intent intent) {
- //獲取傳遞的信息
- Bundle bundle = intent.getExtras();
- String info = bundle.getString("info");
- id = bundle.getInt("id",1);
- NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
- Notification notification = new Notification(R.drawable.alarm, info, System.currentTimeMillis());
- //設置提示框的狀態
- notification.flags = Notification.FLAG_AUTO_CANCEL;
- Intent intentTarget = new Intent(context, AlarmSettingActivity.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
- PendingIntent contentIntent = PendingIntent.getActivity(context, id,intentTarget, PendingIntent.FLAG_UPDATE_CURRENT);
- notification.setLatestEventInfo(context, "鬧鐘"+id, info,
- contentIntent);
- notiManager.notify(id, notification);
- Toast.makeText(context, "時間到了!!!!", Toast.LENGTH_LONG).show();
- }
- }
Notification 主要用於在螢幕頂端顯示通知,能建立狀態列圖示、在展開的狀態列視窗中顯示額外資訊(並啟動 Intent),還能搭配聲音、震動等提示。可透過 id 取消通知:
- notiManager.cancel(id);
此外還有許多可自訂的屬性,例如提示音、震動模式、LED 呼吸燈,以及各種旗標:
- //創建一個NotificationManager的引用
- String ns = Context.NOTIFICATION_SERVICE;
- NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);
- //定義Notification的各種屬性
- int icon = R.drawable.icon; //通知圖標
- CharSequence tickerText = "Hello"; //狀態欄顯示的通知文本提示
- long when = System.currentTimeMillis(); //通知產生的時間,會在通知信息裡顯示
- //用上面的屬性初始化Nofification
- Notification notification = new Notification(icon,tickerText,when);
- /*
- * 添加聲音
- * notification.defaults |=Notification.DEFAULT_SOUND;
- * 或者使用以下幾種方式
- * notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
- * notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
- * 如果想要讓聲音持續重復直到用戶對通知做出反應,則可以在notification的flags字段增加"FLAG_INSISTENT"
- * 如果notification的defaults字段包括了"DEFAULT_SOUND"屬性,則這個屬性將覆蓋sound字段中定義的聲音
- */
- /*
- * 添加振動
- * notification.defaults |= Notification.DEFAULT_VIBRATE;
- * 或者可以定義自己的振動模式:
- * long[] vibrate = {0,100,200,300}; //0毫秒後開始振動,振動100毫秒後停止,再過200毫秒後再次振動300毫秒
- * notification.vibrate = vibrate;
- * long數組可以定義成想要的任何長度
- * 如果notification的defaults字段包括了"DEFAULT_VIBRATE",則這個屬性將覆蓋vibrate字段中定義的振動
- */
- /*
- * 添加LED燈提醒
- * notification.defaults |= Notification.DEFAULT_LIGHTS;
- * 或者可以自己的LED提醒模式:
- * notification.ledARGB = 0xff00ff00;
- * notification.ledOnMS = 300; //亮的時間
- * notification.ledOffMS = 1000; //滅的時間
- * notification.flags |= Notification.FLAG_SHOW_LIGHTS;
- */
- /*
- * 更多的特征屬性
- * notification.flags |= FLAG_AUTO_CANCEL; //在通知欄上點擊此通知後自動清除此通知
- * notification.flags |= FLAG_INSISTENT; //重復發出聲音,直到用戶響應此通知
- * notification.flags |= FLAG_ONGOING_EVENT; //將此通知放到通知欄的"Ongoing"即"正在運行"組中
- * notification.flags |= FLAG_NO_CLEAR; //表明在點擊了通知欄中的"清除通知"後,此通知不清除,
- * //經常與FLAG_ONGOING_EVENT一起使用
- * notification.number = 1; //number字段表示此通知代表的當前事件數量,它將覆蓋在狀態欄圖標的頂部
- * //如果要使用此字段,必須從1開始
- * notification.iconLevel = ; //
- */
Android 本地化:讓同一個 App 說各國語言
一支上架的 Android App,可能會被安裝在幾十個國家的裝置上。使用者期待的是打開來就看到自己熟悉的語言、符合本地習慣的數字與日期格式。這種「讓 App 融入當地環
Android JetPlayer 教學:用 JetCreator 製作互動式音樂內容
Android 平台內建了 JET 引擎,讓應用程式能播放具互動性的 JET 音訊內容——這是一種把音樂拆成多個片段(segment)、可依遊戲狀態即時排列播放的格式,特
Unity3D 發布 APK 並在 Android 模擬器運行的步驟
Unity3D 專案要發布為 Android APK 並在模擬器中執行,需要完成 Java 環境、Android SDK、Unity 發布設定與 ADB 安裝等流程。環境
動手打造自訂 SurfaceView 元件:Android 圖像繪製系列(四)
當標準的 View 無法滿足需求時,自訂元件就成了開發者的好幫手。這一篇就來談談如何封裝一個可重複使用的 SurfaceView,無論是想呈現某個區域的動態畫面,還是打造