Android Alarm 的设置

羊舌阎宝
2023-12-01

一、闹钟的分类

1)从闹钟的设置时间方式分为:以开启启动后的间隔时间和日历时间
2)从硬件上来说分为:1、当cpu休眠时不启动 2、即时cpu休眠时仍然启动
所以有如下四种:
  • ELAPSED_REALTIME—Fires the pending intent based on the amount of time since the device was booted, but doesn't wake up the device. The elapsed time includes any time during which the device was asleep.
  • ELAPSED_REALTIME_WAKEUP—Wakes up the device and fires the pending intent after the specified length of time has elapsed since device boot.
  • RTC—Fires the pending intent at the specified time but does not wake up the device.
  • RTC_WAKEUP—Wakes up the device to fire the pending intent at the specified time

如何设置闹钟

1)设置ELAPSED闹钟
privateAlarmManager alarmMgr;
privatePendingIntent alarmIntent;
...
alarmMgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent =newIntent(context,AlarmReceiver.class);
alarmIntent =PendingIntent.getBroadcast(context,0, intent,0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime()+
        60*1000, alarmIntent);
2)设置RTC
Calendar calendar =Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,14);

// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, alarmIntent);
若需要精确的时间则可以设置:setRepeating()


如何使闹钟开机启动

1)设置开机启动
<uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
2)编写Receiver并在Receiver中设置开启启动的Action
<receiverandroid:name=".SampleBootReceiver"
        android:enabled="false">
    <intent-filter>
        <actionandroid:name="android.intent.action.BOOT_COMPLETED"></action>
    </intent-filter>
</receiver>
3)通过设置packmange的setComponentEnabledSetting属性开启
ComponentName receiver =newComponentName(context,SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP);
这样即使重启闹钟依然有效

 类似资料: