Android随笔之——闹钟制作铺垫之AlarmManager详解
说实话,之前写的两篇博客Android广播机制Broadcast详解、Android时间、日期相关类和方法以及现在要写的,都算是为之后要写的闹钟应用做铺垫,有兴趣的话,大家可以去看看前两篇博客。
一、AlarmManager简介
对于一个闹钟应用的实现,个人觉得最主要的应该要属于AlarmManager了。AlarmManager称为全局定时器,字面意思就是闹钟管理(请原谅我蹩脚的英语),是Android中常用的一种系统级别的提示服务,在特定的时刻为我们广播一个指定的Intent。简单的说就是我们设定一个时间,然后在该时间到来时,AlarmManager为我们广播一个我们设定的Intent,通常我们使用 PendingIntent(这货在调用系统发送短信的时候也有,找个时间温习下Intent,顺带把这个也好好学习下),PendingIntent可以理解为Intent的封装包,简单的说就是在Intent上在加个指定的动作。在使用Intent的时候,我们还需要在执行startActivity、startService或sendBroadcast才能使Intent有用。而PendingIntent的话就是将这个动作包含在内了。
//定义一个PendingIntent对象,此处先照样画葫芦,下次学了再细讲
PendingIntent pi = PendingIntent.getBroadcast(Context, int, Intent, int);
补充:网上有人再说PendingIntent的第二个和第四个参数不重要,其实不然,如果在闹钟这个应用中,你的第二个参数都是同一个常数,那么你之后设的闹钟会把之前的闹钟给覆盖掉,导致时间到了也不提醒的情况。解决办法就是:根据设置闹钟时的时间毫秒数来产生第二个参数。
二、AlarmManager常用方法简介
AlarmManager类提供的常用方法主要有一下几个:
public void set(int type, long triggerAtMillis, PendingIntent operation)
功能:用于设置一次性闹钟,第一个参数表示闹钟类型,第二个参数表示触发这个闹钟要等待的时间,与type相关(不懂英文就查字典吧,我也是查了才理解这个参数的意思的),
第三个参数闹钟响应的动作
参数:type AlarmManager.ELAPSED_REALTIME 在指定的延时过后,发送广播,但不唤醒设备。
AlarmManager.ELAPSED_REALTIME_WAKEUP 在指定的演示后,发送广播,并唤醒设备
AlarmManager.RTC 在指定的时刻,发送广播,但不唤醒设备 时刻是相对于1970-01-01 00:00:00来说的毫秒数
AlarmManager.RTC_WAKEUP 在指定的时刻,发送广播,并唤醒设备
AlarmManager.POWER_OFF_WAKEUP表示闹钟在手机关机状态下也能正常进行提示功能状态值为4;不过我测试的时候并没有这个常量,估计和SDK有关
operation 绑定了闹钟的执行动作,比如发送一个广播、给出提示等等。 public void setExact(int type, long triggerAtMillis, PendingIntent operation)
功能:在规定的时间精确的执行闹钟,这个函数应该是闹钟执行精度比较高吧 public void setRepeating(int type, long triggerAtMills, long intervalMillis, PendingIntent operation)
功能:该方法用于设置重复闹钟,第一个参数表示闹钟类型,第二个参数表示触发这个闹钟要等待的时间,第三个参数表示闹钟两次执行的间隔时间,第三个参数表示闹钟响应动作。 public void setInexactRepeating(int type, long triggerAtMills, long intervalMillis, PendingIntent operation)
功能:设置一个重复闹钟的不精确版本,它相对而言更节能一些,因为系统可能会将几个差不多的闹钟合并为一个来执行,减少设备的唤醒次数。
由于不是精确版,所以这里的intervaMills会略有不同
参数:intervalMillis: INTERVAL_FIFTEEN_MINUTES
INTERVAL_HALF_HOUR
INTERVAL_HOUR
INTERVAL_HALF_DAY
INTERVAL_DAY public void cancel(PendingIntent operation)
功能:取消一个设置的闹钟,移除任意匹配意图的闹钟 public void setTimeZone(String timeZone)
功能:设置系统的默认时区。需要android.permission.SET_TIME_ZONE权限
三、一个简单的闹钟的实例Demo
首先,我们现在AndroidManifest.xml中注册一个广播,如果不清楚可以去看我之前写的博客Android随笔之——Android广播机制Broadcast详解
<receiver android:name=".AlarmReceiver" ><!-- Reveiver名称,如果是内部类静态注册广播,请在内部类前加$ -->
<intent-filter>
<action android:name="android.intent.action.ALARM_RECEIVER" /><!-- 广播接收的Intent --> <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
接着,我们就要编写一个广播接收器,用来接收闹钟的广播事件,进行相关处理
package com.example.alarmmanager; import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast; public class AlarmReceiver extends BroadcastReceiver{ @Override
public void onReceive(Context arg0, Intent arg1) {
//此处可以添加闹钟铃声
System.out.println("我是闹钟,我要叫醒你...");
Toast.makeText(arg0, "我是闹钟,我要叫醒你...", Toast.LENGTH_SHORT).show();
} }
最后,在MainActivity.java写上具体的实现代码
package com.example.alarmmanager; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date; import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener { private AlarmManager alarmManager;
private PendingIntent operation; protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 初始化按钮,并绑定监听事件
findViewById(R.id.ELAPSED_REALTIME_CLOCK).setOnClickListener(this);
findViewById(R.id.ELAPSED_REALTIME_WAKEUP_CLOCK).setOnClickListener(
this);
findViewById(R.id.RTC_CLOCK).setOnClickListener(this);
findViewById(R.id.RTC_WAKEUP_CLOCK).setOnClickListener(this);
findViewById(R.id.repeating_clock).setOnClickListener(this);
findViewById(R.id.cancel_clock).setOnClickListener(this); // 获取AlarmManager对象
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); // 创建Intent对象,action为android.intent.action.ALARM_RECEIVER
Intent intent = new Intent("android.intent.action.ALARM_RECEIVER");
operation = PendingIntent.getBroadcast(this, 0, intent, 0);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ELAPSED_REALTIME_CLOCK:
// 在指定的演示后,发送广播,并唤醒设备
// 延时是要把系统启动的时间SystemClock.elapsedRealtime()算进去的
int triggerAtTime = (int) (SystemClock.elapsedRealtime() + 10 * 1000);
alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, operation);
break;
case R.id.ELAPSED_REALTIME_WAKEUP_CLOCK:
// 在指定的演示后,发送广播,并唤醒设备
// 延时是要把系统启动的时间SystemClock.elapsedRealtime()算进去的
int triggerAtTime1 = (int) (SystemClock.elapsedRealtime() + 5 * 1000);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
triggerAtTime1, operation);
break;
case R.id.RTC_CLOCK:// 在指定的时刻,发送广播,但不唤醒设备
alarmManager.set(AlarmManager.RTC,
getDateMills("2014-08-30 10:06:00"), operation);
break;
case R.id.RTC_WAKEUP_CLOCK:// 在指定的时刻,发送广播,并唤醒设备
alarmManager.set(AlarmManager.RTC_WAKEUP,
getDateMills("2014-08-30 10:10:00"), operation);
break;
case R.id.repeating_clock:// 设置重复闹钟
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 5000, 10000,
operation);
break;
case R.id.cancel_clock:// 取消闹钟
alarmManager.cancel(operation);
break;
default:
break;
}
} @SuppressLint("SimpleDateFormat")
public long getDateMills(String dateStr) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
Date date;
try {
date = format.parse(dateStr);
return date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/ELAPSED_REALTIME_CLOCK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="一次性闹钟:ELAPSED_REALTIME" /> <Button
android:id="@+id/ELAPSED_REALTIME_WAKEUP_CLOCK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="一次性闹钟:ELAPSED_REALTIME_WAKEUP " /> <Button
android:id="@+id/RTC_CLOCK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="一次性闹钟:RTC " /> <Button
android:id="@+id/RTC_WAKEUP_CLOCK"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="一次性闹钟:RTC_WAKEUP_CLOCK" /> <Button
android:id="@+id/repeating_clock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="设置重复闹钟" /> <Button
android:id="@+id/cancel_clock"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取消闹钟" /> </LinearLayout>
这样,一个简单的闹钟就完成了,呼~我的目标是做一个真正可以使用的闹钟,再接再厉!也欢迎大家关注我的博客!
作者:登天路
转载请说明出处:http://www.cnblogs.com/travellife/
源码下载:百度云盘
Android随笔之——闹钟制作铺垫之AlarmManager详解的更多相关文章
- Android 调用图库选择图片实现和参数详解
//选择图片,调用图库 bt4.setOnClickListener(new OnClickListener() { @Override public void o ...
- 详解Android中的四大组件之一:Activity详解
activity的生命周期 activity的四种状态 running:正在运行,处于活动状态,用户可以点击屏幕,是将activity处于栈顶的状态. paused:暂停,处于失去焦点的时候,处于pa ...
- Android textAppearance的属性设置及TextView属性详解
textAppearance的属性设置 android:textAppearance="?android:attr/textAppearanceSmall" android:tex ...
- 【转】ANDROID自定义视图——onLayout源码 流程 思路详解
转载(http://blog.csdn.net/a396901990) 简介: 在自定义view的时候,其实很简单,只需要知道3步骤: 1.测量——onMeasure():决定View的大小 2.布局 ...
- Android Developer -- Bluetooth篇 开发实例之四 API详解
http://www.open-open.com/lib/view/open1390879771695.html 这篇文章将会详细解析BluetoothAdapter的详细api, 包括隐藏方法, 每 ...
- 【Android面试查漏补缺】之Handler详解,带你全面理解Handler消息机制
在安卓面试中,关于 Handler 的问题是必备的,但是这些关于 Handler 的知识点你都知道吗? 一.题目层次 Handler 的基本原理 子线程中怎么使用 Handler MessageQue ...
- Android开发之AlarmManager详解
AlarmManager实质是一个全局的定时器,是Android中常用的一种系统级别的提示服务,在指定时间或周期性启动其它组件(包括Activity,Service,BroadcastReceiver ...
- android AlarmManager 详解
在开发互联网应用时候,我们常常要使用心跳来保证客户端与服务器的连接.怎么完成心跳很关键,在说道客户端心跳功能时,如果使用Timer或者专门开起一个线程来做心跳的工作,会浪费CPU工作时间,而且也会更多 ...
- Android M 特性 Doze and App Standby模式详解
版权声明:本文由郑桂涛原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/185 来源:腾云阁 https://www.qclo ...
随机推荐
- 浏览器的兼容问题 判断IE方法
下面是一些判断ie的常用方法: <!-[if IE 6]> 此处是IE6才会执行的代码 <![endif]-> 还可以给他加个条件,比如判断IE6以下的浏览器: <!-[ ...
- 关于The C compiler "arm-none-eabi-gcc" is not able to compile a simple test program. 的错误自省...
在 GCC ARM Embedded https://launchpad.net/gcc-arm-embedded/ 上面下载了个arm-none-eabi-gcc 用cmake 编译时 #指定C交叉 ...
- Codeforces Round #361 (Div. 2) A
A - Mike and Cellphone Description While swimming at the beach, Mike has accidentally dropped his ce ...
- Github+Jekyll —— 创建个人免费博客(一)从零开始
摘要: 本文中我将介绍一下如何在github上搭建个人Blog(博客),也顺便让我们掌握一下github Pages功能,另外还涉及到Jekyll技术. ======================= ...
- PHP 之 CURL 模拟登陆并获取数据
1.CURL模拟登陆的流程和步骤 2.tempnam 创建一个临时文件 3.使用CURL模拟登陆到PHP100论坛 <?php $cookie_file = tempnam('./temp',' ...
- thrift 服务端linux C ++ 与客户端 windows python 环境配置(thrift 自带tutorial为例)
关于Thrift文档化的确是做的不好.摸索了很久才终于把跨linux与windows跨C++与python语言的配置成功完成.以下是步骤: 1) Linux下环境配置 ...
- 解决Ionic的ion-slide-box 2条数据渲染问题
当slider数据列表是动态获取时,如果数据结果只有2条数据时,slider列表会多复制俩个,通过下面的slideChange方法做个判断可以解决这个bug 第一步:添加slideChande方法 & ...
- MySQL数据表range分区例子
某些行业数据量的增长速度极快,随着数据库中数据量的急速膨胀,数据库的插入和查询效率越来越低.此时,除了程序代码和查询语句外,还得在数据库的结构上做点更改:在一个主读辅写的数据库中,当数据表数据超过10 ...
- WPF中的Pack URI
更多资源:http://denghejun.github.io 问题 说来也简单:首先,我在WPF项目中建立了一个用户自定义控件(CustomControl),VS模板为我们自动生成了 CustomC ...
- 七种机器内部排序的原理与C语言实现,并计算它们的比较次数与移动次数。
内部排序是指待排序列完全存放在内存中所进行的排序过程,适合不太大的元素序列. 排序是计算机程序设计中的一种重要操作,其功能是对一个数据元素集合或序列重新排列成一个按数据元素某个相知有序的序列.排序分为 ...