Android Alarm 的设置

本文介绍了闹钟的分类及设置方法,包括基于启动后间隔时间的ELAPSED_REALTIME和基于日历时间的RTC两种主要类型。同时,还详细说明了如何设置不同类型的闹钟,并提供了使闹钟在设备开机时自动启动的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、闹钟的分类

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);
这样即使重启闹钟依然有效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值