AlarmManager简介

AlarmManager实质是一个全局的定时器,是Android中常用的一种系统级别的提示服务,在指定时间或周期性启动其它组件(包括Activity,Service,BroadcastReceiver)。本文将讲解一下如何使用AlarmManager实现定时提醒功能。

闹钟配置

周期闹钟

Intent intent = new Intent();intent.setAction(GlobalValues.TIMER_ACTION_REPEATING);PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5 * 1000, 3 * 1000, sender);
setRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

该方法用于设置周期性执行的定时服务。type:闹钟类型,startTime:闹钟首次执行时间,intervalTime:闹钟两次执行的间隔时间,pi:闹钟响应动作。

setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

该方法也用于设置周期定式服务,与上一种类似。不过其两个闹钟执行的间隔时间不是固定的。它相对而言更省电一些,因为系统可能会将几个差不多的闹钟合并为一个来执行,减少设备的唤醒次数。

intervalTime内置变量

间隔一天:   INTERVAL_DAY
间隔半天:   INTERVAL_HALF_DAY
间隔15分钟:  INTERVAL_FIFTEEN_MINUTES
间隔半个小时: INTERVAL_HALF_HOUR
间隔一个小时: INTERVAL_HOUR

定时闹钟

//获得系统提供的AlarmManager服务的对象AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);//Intent设置要启动的组件,这里启动广播Intent myIntent = new Intent();myIntent.setAction(GlobalValues.TIMER_ACTION);//PendingIntent对象设置动作,启动的是Activity还是Service,或广播!PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);//注册闹钟alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5 * 1000, sender);
set(int type,long startTime,PendingIntent pi)

该方法用于设置一次性定时服务。type:闹钟类型,startTime:闹钟执行时间,pi:闹钟响应动作。

取消闹钟

Intent myIntent = new Intent();myIntent.setAction(GlobalValues.TIMER_ACTION);//myIntent.setAction(GlobalValues.TIMER_ACTION_REPEATING);PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);alarm.cancel(sender);

设置多个闹钟:

若连续设置多个闹钟,则只有最后一个闹钟会生效,那么这种情况我们怎么处理呢?其实很简单。我们可以给每个闹钟设置唯一的id,传入getBroadcast()第二个参数。在这里我是每设置一个id则自增1存入Shareprefrence里,保证id唯一性。

 //给每个闹钟设置不同ID防止覆盖int alarmId = SharedPreUtils.getInteger(context, "alarm_id", 0);SharedPreUtils.setInteger(context, "alarm_id", ++alarmId);PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);

在取消闹钟时我们也可以根据这个id关闭不同的闹钟。

参数详解

type:闹钟类型

ELAPSED_REALTIME:在指定的延时过后,发送广播,但不唤醒设备(闹钟在睡眠状态下不可用)。如果在系统休眠时闹钟触发,它将不会被传递,直到下一次设备唤醒。

ELAPSED_REALTIME_WAKEUP:在指定的延时过后,发送广播,并唤醒设备(即使关机也会执行operation所对应的组件) 。延时是要把系统启动的时间SystemClock.elapsedRealtime()算进去的。

RTC:指定当系统调用System.currentTimeMillis()方法返回的值与triggerAtTime相等时启动operation所对应的设备(在指定的时刻,发送广播,但不唤醒设备)。如果在系统休眠时闹钟触发,它将不会被传递,直到下一次设备唤醒(闹钟在睡眠状态下不可用)。

RTC_WAKEUP:指定当系统调用System.currentTimeMillis()方法返回的值与triggerAtTime相等时启动operation所对应的设备(在指定的时刻,发送广播,并唤醒设备)。即使系统关机也会执行operation所对应的组件。

POWER_OFF_WAKEUP:表示闹钟在手机关机状态下也能正常进行提示功能,所以是5个状态中用的最多的状态之一,该状态下闹钟也是用绝对时间,状态值为4;不过本状态好像受SDK版本影响,某些版本并不支持。

long intervalTime:执行时间

闹钟的第一次执行时间,以毫秒为单位,可以自定义时间,不过一般使用当前时间。需要注意的是,本属性与第一个属性(type)密切相关,如果第一个参数对应的闹钟使用的是相对时间(ELAPSED_REALTIME和ELAPSED_REALTIME_WAKEUP),那么本属性就得使用相对时间(相对于系统启动时间来说),比如当前时间就表示为:SystemClock.elapsedRealtime();如果第一个参数对应的闹钟使用的是绝对时间(RTC、RTC_WAKEUP、POWER_OFF_WAKEUP),那么本属性就得使用绝对时间,比如当前时间就表示为:System.currentTimeMillis()

long startTime:间隔时间

对于周期定时方式来说,存在本属性,表示两次闹钟执行的间隔时间,也是以毫秒为单位。

PendingIntent pi:执行动作

是闹钟的执行动作,比如发送一个广播、给出提示等等。PendingIntent是Intent的封装类。需要注意的是,如果是通过启动服务来实现闹钟提示的话,PendingIntent对象的获取就应该采用Pending.getService(Context c,int i,Intent intent,int j)方法;如果是通过广播来实现闹钟提示的话,PendingIntent对象的获取就应该采用PendingIntent.getBroadcast(Context c,int i,Intent intent,int j)方法;如果是采用Activity的方式来实现闹钟提示的话,PendingIntent对象的获取就应该采用PendingIntent.getActivity(Context c,int i,Intent intent,int j)方法。如果这三种方法错用了的话,虽然不会报错,但是看不到闹钟提示效果。。

广播配置

新建闹钟BroadCastReceiver:

public class AlarmReceiver extends BroadcastReceiver { private NotificationManager m_notificationMgr = null; private static final int NOTIFICATION_FLAG = 3; @Override public void onReceive(Context context, Intent intent) {  m_notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVIC  if (intent.getAction().equals(GlobalValues.TIMER_ACTION_REPEATING)) {   Log.e("alarm_receiver", "周期闹钟");  } else if (intent.getAction().equals(GlobalValues.TIMER_ACTION)) {   Log.e("alarm_receiver", "定时闹钟");      Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);   Intent intent1 = new Intent(context, WriteDiaryActivity.class);   PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent1, 0);   Notification notify = new Notification.Builder(context)     .setSmallIcon(R.drawable.logo) // 设置状态栏中的小图片,尺寸一般建议在24×24     .setLargeIcon(bitmap) // 这里也可以设置大图标     .setTicker("亲情日历") // 设置显示的提示文字     .setContentTitle("亲情日历") // 设置显示的标题     .setContentText("您有日记提醒哦") // 消息的详细内容     .setContentIntent(pendingIntent) // 关联PendingIntent     .setNumber(1) // 在TextView的右方显示的数字,可以在外部定义一个变量,点击累加setNumber(count),这时显示的和     .getNotification(); // 需要注意build()是在API level16及之后增加的,在API11中可以使用getNotificatin()来   notify.flags |= Notification.FLAG_AUTO_CANCEL;   NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIF   manager.notify(NOTIFICATION_FLAG, notify);   bitmap.recycle(); //回收bitmap  } }}

注册BroadCastReceiver:

最后别忘了在清单里注册广播。

      

附件

常量:

public class GlobalValues { // 周期性的闹钟 public final static String TIMER_ACTION_REPEATING = "com.e_eduspace.TIMER_ACTION_REPEATING"; // 定时闹钟 public final static String TIMER_ACTION = "com.e_eduspace.TIMER_ACTION";}

工具类

package com.e_eduspace.familycalendar.util;import android.app.AlarmManager;import android.app.PendingIntent;import android.content.Context;import android.content.Intent;import com.prolificinteractive.materialcalendarview.CalendarDay;/** * 闹钟定时工具类 * * @author xulei * @time 2016/12/13 10:03 */public class AlarmTimer { /**  * 设置周期性闹钟  *  * @param context  * @param firstTime  * @param cycTime  * @param action  * @param AlarmManagerType 闹钟的类型,常用的有5个值:AlarmManager.ELAPSED_REALTIME、  *       AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、  *       AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP  */ public static void setRepeatingAlarmTimer(Context context, long firstTime,            long cycTime, String action, int AlarmManagerType) {  Intent myIntent = new Intent();  myIntent.setAction(action);  PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent, 0);  AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  alarm.setRepeating(AlarmManagerType, firstTime, cycTime, sender);  //param1:闹钟类型,param1:闹钟首次执行时间,param1:闹钟两次执行的间隔时间,param1:闹钟响应动作。 } /**  * 设置定时闹钟  *  * @param context  * @param cycTime  * @param action  * @param AlarmManagerType 闹钟的类型,常用的有5个值:AlarmManager.ELAPSED_REALTIME、  *       AlarmManager.ELAPSED_REALTIME_WAKEUP、AlarmManager.RTC、  *       AlarmManager.RTC_WAKEUP、AlarmManager.POWER_OFF_WAKEUP  */ public static void setAlarmTimer(Context context, long cycTime,          String action, int AlarmManagerType, CalendarDay date) {  Intent myIntent = new Intent();  //传递定时日期  myIntent.putExtra("date", date);  myIntent.setAction(action);  //给每个闹钟设置不同ID防止覆盖  int alarmId = SharedPreUtils.getInteger(context, "alarm_id", 0);  SharedPreUtils.setInteger(context, "alarm_id", ++alarmId);  PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);  AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  alarm.set(AlarmManagerType, cycTime, sender); } /**  * 取消闹钟  *  * @param context  * @param action  */ public static void cancelAlarmTimer(Context context, String action) {  Intent myIntent = new Intent();  myIntent.setAction(action);  PendingIntent sender = PendingIntent.getBroadcast(context, 0, myIntent,0);  AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  alarm.cancel(sender); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多相关文章

  1. Android(安卓)开机广播BOOT_COMPLETED延迟接收问题解决
  2. Android(安卓)ListView 有时候设置setDividerHeight无效的原因
  3. android AlarmManager闹钟设置多次只响应一次和响应多次以及传参
  4. Android(安卓)Scroller简介 ---- 界面滚动
  5. android Activity如何横屏显示?如何解决Activity在设置横屏时候会
  6. 安卓控件之文本框(TextView)
  7. 【安卓】选项卡之顶部选项卡(简易)
  8. Android(安卓)Permission完整版
  9. Android(安卓)Studio的使用第一篇优化篇

随机推荐

  1. GridView相关
  2. Android Activity 的四种启动模式 lunchM
  3. android 布局学习
  4. Android(安卓)网络图片加载
  5. Android ListView 设置
  6. 海康威视Android SDK,即萤石Android SDK
  7. 开发Android下纯C程序时,打开时提示not f
  8. 简述修改logo以及文字
  9. Android系统自带主题样式(android:theme),An
  10. Android界面——LinearLayout和RelativeL