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

Android 進階:動手做鬧鐘,徹底搞懂 Alarm 與 Notification

編輯:Android 開發實例

無意間看到 Alarm 這個類別,覺得相當有意思,而且實務上應該很常用,於是查了些資料並親手做了一個 demo。

認識 Alarm

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():

  1. public class AlarmSettingActivity extends Activity {  
  2.     private Button setbutton;    
  3.     private Button canclebutton;    
  4.     
  5.     private TextView mTextView;    
  6.     
  7.     private Calendar calendar;    
  8.       
  9.     private AlarmManager am;    
  10.     
  11.     @Override    
  12.     public void onCreate(Bundle savedInstanceState) {    
  13.         super.onCreate(savedInstanceState);    
  14.     
  15.         setContentView(R.layout.main);    
  16.           
  17.         //獲得Alarm管理實例  
  18.         am = (AlarmManager) getSystemService(ALARM_SERVICE);    
  19.           
  20.         calendar = Calendar.getInstance();    
  21.     
  22.         mTextView = (TextView) findViewById(R.id.textinfo);    
  23.         setbutton = (Button) findViewById(R.id.setbutton);    
  24.         canclebutton = (Button) findViewById(R.id.canclebutton);    
  25.     
  26.         setbutton.setOnClickListener(new View.OnClickListener() {    
  27.             public void onClick(View v) {    
  28.                 calendar.setTimeInMillis(System.currentTimeMillis());    
  29.                 int mHour = calendar.get(Calendar.HOUR_OF_DAY);    
  30.                 int mMinute = calendar.get(Calendar.MINUTE);    
  31.                 new TimePickerDialog(AlarmSettingActivity.this,    
  32.                     new TimePickerDialog.OnTimeSetListener() {    
  33.                         public void onTimeSet(TimePicker view,    
  34.                                 int hourOfDay, int minute) {    
  35.                             calendar.setTimeInMillis(System    
  36.                                     .currentTimeMillis());    
  37.                             calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);    
  38.                             calendar.set(Calendar.MINUTE, minute);    
  39.                             calendar.set(Calendar.SECOND, 0);    
  40.                             calendar.set(Calendar.MILLISECOND, 0);    
  41.                             Intent intent = new Intent(AlarmSettingActivity.this, AlarmBroadCastReceiver.class);  
  42.                             //這裡可以傳遞消息,譬如提醒信息  
  43.                             Bundle bundle = new Bundle();  
  44.                             bundle.putString("info", "該起床啦 ~~~~~");  
  45.                             bundle.putInt("id", new Random().nextInt(100));  
  46.                             intent.putExtras(bundle);  
  47.                             //獲得一個可以掛起的Intent  
  48.                             PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmSettingActivity.this, 0,intent, 0);    
  49.                             /* 設置鬧鐘 */    
  50.                             am.set(AlarmManager.RTC_WAKEUP, calendar    
  51.                                     .getTimeInMillis(), pendingIntent);    
  52.                             /* 設置周期鬧 */    
  53.                             am.setRepeating(AlarmManager.RTC_WAKEUP, System    
  54.                                     .currentTimeMillis()    
  55.                                     + (10 * 1000), (24 * 60 * 60 * 1000),    
  56.                                     pendingIntent);    
  57.                             String tmpS = "設置鬧鐘時間為" + format(hourOfDay)    
  58.                                     + ":" + format(minute);    
  59.                             mTextView.setText(tmpS);    
  60.                         }    
  61.                     }, mHour, mMinute, true).show();    
  62.                 }  
  63.         });    
  64.     
  65.         canclebutton.setOnClickListener(new View.OnClickListener() {    
  66.             public void onClick(View v) {    
  67.                 Intent intent = new Intent(AlarmSettingActivity.this, AlarmBroadCastReceiver.class);    
  68.                 PendingIntent pendingIntent = PendingIntent.getBroadcast(    
  69.                         AlarmSettingActivity.this, 0, intent, 0);    
  70.                 //取消該Intent  
  71.                 am.cancel(pendingIntent);    
  72.                 mTextView.setText("鬧鐘已取消!");    
  73.                 }  
  74.         });    
  75.     }  
  76.     
  77.     //格式化字符串 不滿兩位 前面補0  
  78.     private String format(int x) {    
  79.         String s = "" + x;    
  80.         if (s.length() == 1)    
  81.             s = "0" + s;    
  82.         return s;    
  83.     }    
  84. } 

這裡用到了 PendingIntent。顧名思義,pending 就是「掛起」的意思,它的功能與 Intent 類似,內部同樣持有 Intent 的引用,主要差別在生命週期:由於 Alarm 不依賴應用,而 Intent 依賴應用,因此改用 PendingIntent——它的生命週期由系統管理,即使建立它的應用被關閉,仍能存在並在別的行程中使用。

以 BroadcastReceiver 接收並發出通知

鬧鐘觸發時,透過 BroadcastReceiver 接收訊息,再以 Notification 在狀態列顯示提示:

  1. public class AlarmBroadCastReceiver extends BroadcastReceiver{  
  2.     private int id;  
  3.     @Override 
  4.     public void onReceive(Context context, Intent intent) {  
  5.         //獲取傳遞的信息  
  6.         Bundle bundle = intent.getExtras();  
  7.         String info = bundle.getString("info");  
  8.         id = bundle.getInt("id",1);  
  9.         NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);  
  10.         Notification notification = new Notification(R.drawable.alarm, info, System.currentTimeMillis());  
  11.         //設置提示框的狀態  
  12.         notification.flags = Notification.FLAG_AUTO_CANCEL;  
  13.         Intent intentTarget = new Intent(context, AlarmSettingActivity.class);  
  14.         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);  
  15.         PendingIntent contentIntent = PendingIntent.getActivity(context, id,intentTarget, PendingIntent.FLAG_UPDATE_CURRENT);  
  16.         notification.setLatestEventInfo(context, "鬧鐘"+id, info, 
  17.                 contentIntent);  
  18.         notiManager.notify(id, notification);  
  19.           
  20.           
  21.         Toast.makeText(context, "時間到了!!!!", Toast.LENGTH_LONG).show();  
  22.     }  
  23. }  

Notification 主要用於在螢幕頂端顯示通知,能建立狀態列圖示、在展開的狀態列視窗中顯示額外資訊(並啟動 Intent),還能搭配聲音、震動等提示。可透過 id 取消通知:

  1. notiManager.cancel(id); 

此外還有許多可自訂的屬性,例如提示音、震動模式、LED 呼吸燈,以及各種旗標:

  1. //創建一個NotificationManager的引用  
  2. String ns = Context.NOTIFICATION_SERVICE;  
  3. NotificationManager mNotificationManager = (NotificationManager)getSystemService(ns);  
  4. //定義Notification的各種屬性  
  5. int icon = R.drawable.icon; //通知圖標  
  6. CharSequence tickerText = "Hello"; //狀態欄顯示的通知文本提示  
  7. long when = System.currentTimeMillis(); //通知產生的時間,會在通知信息裡顯示  
  8. //用上面的屬性初始化Nofification  
  9. Notification notification = new Notification(icon,tickerText,when);  
  10. /*  
  11. * 添加聲音  
  12. * notification.defaults |=Notification.DEFAULT_SOUND;  
  13. * 或者使用以下幾種方式  
  14. * notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");  
  15. * notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");  
  16. * 如果想要讓聲音持續重復直到用戶對通知做出反應,則可以在notification的flags字段增加"FLAG_INSISTENT"  
  17. * 如果notification的defaults字段包括了"DEFAULT_SOUND"屬性,則這個屬性將覆蓋sound字段中定義的聲音  
  18. */ 
  19. /*  
  20. * 添加振動  
  21. * notification.defaults |= Notification.DEFAULT_VIBRATE;  
  22. * 或者可以定義自己的振動模式:  
  23. * long[] vibrate = {0,100,200,300}; //0毫秒後開始振動,振動100毫秒後停止,再過200毫秒後再次振動300毫秒  
  24. * notification.vibrate = vibrate;  
  25. * long數組可以定義成想要的任何長度  
  26. * 如果notification的defaults字段包括了"DEFAULT_VIBRATE",則這個屬性將覆蓋vibrate字段中定義的振動  
  27. */ 
  28. /*  
  29. * 添加LED燈提醒  
  30. * notification.defaults |= Notification.DEFAULT_LIGHTS;  
  31. * 或者可以自己的LED提醒模式:  
  32. * notification.ledARGB = 0xff00ff00;  
  33. * notification.ledOnMS = 300; //亮的時間  
  34. * notification.ledOffMS = 1000; //滅的時間  
  35. * notification.flags |= Notification.FLAG_SHOW_LIGHTS;  
  36. */ 
  37. /*  
  38. * 更多的特征屬性  
  39. * notification.flags |= FLAG_AUTO_CANCEL; //在通知欄上點擊此通知後自動清除此通知  
  40. * notification.flags |= FLAG_INSISTENT; //重復發出聲音,直到用戶響應此通知  
  41. * notification.flags |= FLAG_ONGOING_EVENT; //將此通知放到通知欄的"Ongoing"即"正在運行"組中  
  42. * notification.flags |= FLAG_NO_CLEAR; //表明在點擊了通知欄中的"清除通知"後,此通知不清除,  
  43. * //經常與FLAG_ONGOING_EVENT一起使用  
  44. * notification.number = 1; //number字段表示此通知代表的當前事件數量,它將覆蓋在狀態欄圖標的頂部  
  45. * //如果要使用此字段,必須從1開始  
  46. * notification.iconLevel = ; //  
  47. */  
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved