導讀:Android的鬧鐘實現(xiàn)機制很簡單, 只需要調用AlarmManager.set()將鬧鈴時間記錄到系統(tǒng)中,當鬧鈴時間到后,系統(tǒng)會給應用程序發(fā)送廣播,我們只需要去注冊廣播接收器就可以了。
本文分三部分講解如何實現(xiàn)鬧鐘:
目錄:
1. 設置鬧鈴時間;
2. 接收鬧鈴事件廣播;
3. 重開機后重新計算并設置鬧鈴時間;
正文:
1. 設置鬧鈴時間(毫秒)
1 | private void setAlarmTime(Context context, long timeInMillis) { |
2 | AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); |
3 | Intent intent = new Intent(”android.alarm.demo.action“); |
4 | PendingIntent sender = PendingIntent.getBroadcast( |
5 | context, 0 , intent, PendingIntent.FLAG_CANCEL_CURRENT); |
6 | int interval = 60 * 1000 ; |
7 | am.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, interval, sender) |
2. 接收鬧鈴事件廣播
1 | public class AlarmReceiver extends BroadcastReceiver { |
2 | public void onReceive(Context context, Intent intent) { |
3 | if (”android.alarm.demo.action“.equals(intent.getAction())) { |
當然,Receiver是需要在Manifest.xml中注冊的:
1 | <receiver android:name= "AlarmReceiver" > |
3 | <action android:name= "android.alarm.demo.action" /> |
3. 重開機后重新計算并設置鬧鈴時間
當然要有一個BootReceiver:
1 | public class BootReceiver extends BroadcastReceiver { |
2 | public void onReceive(Context context, Intent intent) { |
3 | String action = intent.getAction(); |
4 | if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { |
當然,也需要注冊:
1 | <receiver android:name= "BootReceiver" > |
3 | <action android:name= "android.intent.action.BOOT_COMPLETED" /> |
鬧鐘實現(xiàn)原理其實就這么多,至于具體的細節(jié)比如鬧鈴時間存儲及計算, 界面顯示及鬧鈴提示方式,每個人的想法做法都會不一樣,就不贅述。
|