本文分三部分講解如何實(shí)現鬧鐘:
目錄:
1. 設置鬧鈴時(shí)間;
2. 接收鬧鈴事件廣播;
3. 重開(kāi)機后重新計算并設置鬧鈴時(shí)間;
正文:
1. 設置鬧鈴時(shí)間(毫秒)
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. 重開(kāi)機后重新計算并設置鬧鈴時(shí)間 當然要有一個(gè)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" /> |
鬧鐘實(shí)現原理其實(shí)就這么多,至于具體的細節比如鬧鈴時(shí)間存儲及計算, 界面顯示及鬧鈴提示方式,每個(gè)人的想法做法都會(huì )不一樣,就不贅述。