您的位置:首页 > 移动开发 > Android开发

Android 闹钟设置详解

2016-06-11 22:50 435 查看

一、闹钟的分类

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;
//首先获取闹钟的service
alarmMgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent =new Intent(context,AlarmReceiver.class);
//设置PendingIntent 即闹铃启动后要做的事情
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);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
若需要精确的时间则可以设置:setRepeating()


三、如何使闹钟开机启动

1)设置开机启动

<receiver android:name=".SampleBootReceiver"
android:enabled="false">
<intent-filter>
<actionandroid:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>


3)通过设置packmange的setComponentEnabledSetting属性开启

ComponentName receiver =new ComponentName(context,SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
//手动的设置ComponentName的属性为不被杀死
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
这样即使重启闹钟依然有效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: