Alarm Clock AlarmManager PendingIntent

2010-06-21  来源:本站原创  分类:Mobile  人气:351 

Based on the android built-in alarm function in brief, to allow developers to friends understanding OPhone platform based on client / server programming model, and how to use OPhone alarm wake-up function provided by the system. At the same time, the paper also PendingIntent do some brief, and an example program to demonstrate how PendingIntent the alarm clock alarm services, applications and systems linked.

First, the alarm function

Alarm clock application used as the everyday one of the basic applications, its importance is self-evident. Alarm system in OPhone services not only to the alarm clock application service, the most important thing is to use the services provided by the wake-up alarm capability to do timer. This application is not running or even if there is no boot, as long as its registered alarm, then the alarm to the time, OPhone system can automatically start the application process, which is called the alarm to "wake up" function.

In OPhone system, the underlying system provides two types of clock, clock software clock and hard and soft clock is what we often say Timer, hardware clock is the RTC. System under normal operation, Timer to provide time services and alarms, while in the system to sleep, the time of service and alarms to be responsible by the RTC. For the upper applications, we do not need to worry about is the timer or RTC to provide services for us, because OPhone System Framework layer to the underlying details of the package and do provide unified API. This API is called his AlarmManager. In OPhone system is interesting that there is a corresponding AlarmManage AlarmManagerServie service program, the service program is to provide the alarm service is true, it is mainly down to maintain the application for registration and timely to set various alarm will trigger the alarm to the downtown Bell Equipment (in OPhone system, linux device called the realization of "/ dev / alarm"), and has been monitoring the alarm device, once the alarm is triggered or alarm events, AlarmManagerServie service program will traverse the alarm list to find the appropriate registration and issue radio alarm. The service program at system startup when the system service routine system_service start and initialize the alarm device (/ dev / alarm). Of course, in the JAVA layer AlarmManagerService and Linux Alarm driver programming interface layer between the well package, that is JNI.

AlarmManager applications and services will be separated, the so application developers do not care about specific services, but directly through AlarmManager to use this service. This may be the client / service model of the benefits of it. AlarmManager and AlarmManagerServie by Binder to between communicate , they are among the many to one relationship. In OPhone system, AlarmManage provides three interfaces 5 types of alarm services:

  • 3 API Call Interface:
    <! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> void cancel (PendingIntent operation)
    / / Cancel the registered alarm and parameter matching
    void set (int type, long triggerAtTime, PendingIntent operation)
    / / Register a new alarm
    void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)
    / / Register a repeat type of alarm
    void setTimeZone (String timeZone)
    / / Set time zone
  • 5 kinds of alarm types:
    <! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> public static final int ELAPSED_REALTIME
    / / When the system goes into sleep state, this type of alarm will not wake the system. Until the system is awakened before the next pass it, the time spent in the alarm time is relative, is from the system startup time, including sleep time, you can call SystemClock.elapsedRealtime () access. System value is 3 (0x00000003).

    public static final int ELAPSED_REALTIME_WAKEUP
    / / Can wake the system, use the same ELAPSED_REALTIME, the system value is 2 (0x00000002).

    public static final int RTC
    / / When the system goes into sleep state, this type of alarm will not wake the system. Until the system is awakened before the next pass it, the alarm time is used in absolute time, time is UTC time used, by calling System.currentTimeMillis () access. System value is 1 (0x00000001).

    public static final int RTC_WAKEUP
    / / Can wake the system, use the type with the RTC, the system value is 0 (0x00000000).

    Public static final int POWER_OFF_WAKEUP
    / / Can wake the system, it is a shutdown alarm, that device is turned off can also wake up the system, so we call it off the alarm. RTC to use the same type, the system value of 4 (0x00000004).

Developers can OPhone SDK to obtain more AlarmManager the relevant details for the package where he is: Android.app.AlarmManager

With OPhone system version of the continuous upgrading of these interfaces, and alarm types may be some adjustments, but its use will not change the basic

Second, set the alarm clock and reminders

We first through an intuitive UI to feel OPhone system embedded alarm clock program is how to respond to user settings and automatic reminders of: (as shown in Figure 4)

Alarm Clock AlarmManager PendingIntent

Alarm Clock AlarmManager PendingIntent

Figure 4 above intuitive told embedded developers how to use OPhone alarm clock applications, but developers may be more concerned with how to achieve these functions through the code. How to set an alarm for example, the set what type of alarm, and how to obtain the alarm time has come and remind the user. Based on these problems, we gradually in the following sections to present.

2.1 Setting the alarm

In the first section, we have already mentioned OPhone system AlarmManagerService provides two set the alarm API, they are:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> void set (int type, long triggerAtTime, PendingIntent operation)
void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)

In OPhone 1.5 version adds another API.

The following program demonstrates how to set an alarm.

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> / when set alarm is triggered, Ophone system will broadcast an Intent, of course, we need to create a new alarm
/ / Register an alarm when the event sink object AlarmReceiver, the receiving object can also be in the / / AndroidManifest.xml in the release can also be registered dynamically in code.

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.os.Bundle;
import java.util.Calendar;

/ / Create a PendingIntent
Intent intent = new Intent (ALARM_ALERT_ACTION);
intent.putExtra (ID, id);
intent.putExtra (TIME, atTimeInMillis);
PendingIntent sender = PendingIntent.getBroadcast (
context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
/ / Get AlarmMnager and register a new alarm,
/ / Set the alarm off

AlarmManager am = (AlarmManager) getSystemService (ALARM_SERVICE);
am.set (AlarmManager.POWER_OFF_WAKEUP, atTimeInMillis, sender);

/ / Set the alarm repetitive
/ / We want the alarm to go off 30 seconds from now.
long firstTime = SystemClock.elapsedRealtime ();
firstTime + = 15 * 1000;

/ / Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService (ALARM_SERVICE);
am.setRepeating (AlarmManager.POWER_OFF_WAKEUP,
firstTime, 15 * 1000, sender);

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -->// in AndroidManifest . xml register
<Receiver android: name = "AlarmReceiver">
<Intent - filter>
<Action android: name = "com.android.alarmclock.ALARM_ALERT" />
</ Intent - filter>
</ Receiver>

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -->// application register during program execution

AlarmReceiver mAlarmReceiver;
IntentFilter filter = new IntentFilter ();
filter. addAction ("com.android.alarmclock.ALARM_ALERT");
context.registerReceiver (mAlarmReceiver, filter);

public class AlarmReceiver extends BroadcastReceiver (
@ Override
public void onReceive (Context context, Intent intent) (

)
)

2.2 alarm to remind <br /> in OPhone system, when the application is set the alarm time comes, OPhone system AlarmManagerService will get an alarm from the system underlying the event and to maintain the queue from its own out of their match the alarm, and then through its application for registration PendingIntent to send back to the alarm event application.

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> PendingIntent.send ( );

When our application will be started after receipt of the Intent of the Activity appropriate to remind the user to the alarm time.

Code is as follows:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> package com.android . alarmclock;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.os.Handler;
import android.os.PowerManager;
import android.os.SystemClock;

public class AlarmReceiver extends BroadcastReceiver (
@ Override
public void onReceive (Context context, Intent intent) (
long now = System.currentTimeMillis ();
int id = intent.getIntExtra (Alarms.ID, 0);
long setFor = intent.getLongExtra (Alarms.TIME, 0);
Intent fireAlarm = new Intent (context, AlarmAlert.class);
fireAlarm.putExtra (Alarms.ID, id);
fireAlarm.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
/ / Start a new UI object to remind
context.startActivity (fireAlarm);
)
)

3, PendingIntent
In the previous chapter, we register the alarm in the event ﹑ send alarm when there was an important parameter PendingIntent. Intent can be said that PendingIntent further package, he not only includes a description of Intent is the implementation of Intent behavior (This definition may be less strict), if an order of Intent than Zuocheng words, PendingIntent is more like an order under people, because it has to be responsible for issuing the order to go, to be responsible for orders sent after processing, such as sending successful acceptance of orders for goods to be ready to send after the failure to re-send or cancel the order and other operations. Developers can call getActivity (Context, int, Intent, int), getBroadcast (Context, int, Intent, int), getService (Context, int, Intent, int) function to get a PendingIntent instance.

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> public static PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)

PendingIntent obtained by the function will play a broadcast function, as called Context.sendBroadcast () function is the same. When the system through its intent to send a broadcast to be used when the form, and will be included in the intent of intent to receive the corresponding object, of course, the object can be specified when creating PendingIntent can also be described by such as ACTION and CATEGORY to OPhone behavior management system to automatically locate the object.

Example code is as follows:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> Intent intent = new Intent (AlarmController.this, OneShotAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast (AlarmController.this,
0, intent, 0);

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> Public static PendingIntent getActivity (Context, int, Intent, int)

PendingIntent obtained by the function can start a new activity, just call Context.startActivity (Intent) as. But worth noting is to find the new Activity no longer exists in the Activity when the current process. Our intent must use Intent.FLAG_ACTIVITY_NEW_TASK.

Example code is as follows:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -->// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity (this, 0,
new Intent (this, AlarmService.class), 0);

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)

PengdingIntent obtained by the function can start a new Service, as called Context.startService () the same.

Example code is as follows:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> / / Create an IntentSender that will launch our service, to be scheduled
/ / With the alarm manager.
mAlarmSender = PendingIntent.getService (AlarmService.this,
0, new Intent (AlarmService.this, AlarmService_Service.class), 0);

4, PendingInent and service

In OPhone system programming, a complete OPhone application can have 4 modules need to create, they are:

Activity, Broadcast intent Receiver, Service, Content Provider. Service as part of a OPhone applications, usually running in the background, there is no interaction between him and the user. Like other application objects running in their process as the main thread. So this means that it is possible to enter the long run to wait for the result without the user's corresponding application. Therefore, the development time to design the program to be considered, if a Service to do some data processing time (such as playing MP3 , or Wangluo download), the necessary make the work Qiehuan to your thread space to perform.

Example code is as follows:

<! - <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware) <br /> http://www.CodeHighlighter.com/ <br /> <br /> -> import android.app . Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.widget.Toast;

/ / Define a Service object
public class AlarmService_Service extends Service (
NotificationManager mNM;
public void onCreate () (
/ / Create a thread to run the Runnable
Thread thr = new Thread (null, mTask, "AlarmService_Service");
thr.start ();
)
public void onDestroy () (
)
Runnable mTask = new Runnable () (
public void run () (
/ / Usually we can design a long run here, the function
long endTime = System.currentTimeMillis () + 15 * 1000;
while (System.currentTimeMillis () <endTime) (
synchronized (mBinder) (
try (
mBinder.wait (endTime - System.currentTimeMillis ());
) Catch (Exception e) (
)
)
)

/ / Stop Service
AlarmService_Service.this.stopSelf ();
)
);

/ / In the preparation of Service code, you can not achieve onStart, onStop and other functions, but it must be realized onBind function
public IBinder onBind (Intent intent) (
return mBinder;
)
/ * By the client object can communicate
* /
private final IBinder mBinder = new Binder () (
@ Override
protected boolean onTransact (int code, Parcel data, Parcel reply,
int flags) throws RemoteException (
return super.onTransact (code, data, reply, flags);
)
);
)

Summary: This article introduces how to use AlarmManager wake timing functions, and the meaning of the various alarm and API use cases, I hope the reader friends in OPhone application programming in the proper use of the AlarmManager, serve. We also introduced an important concept PendingIntent, by PendingIntent parameter analysis, the reader believe that the use of friends on the PendingIntent have a basic understanding.

相关文章
  • Alarm Clock AlarmManager PendingIntent 2010-06-21

    Based on the android built-in alarm function in brief, to allow developers to friends understanding OPhone platform based on client / server programming model, and how to use OPhone alarm wake-up function provided by the system. At the same time, the

  • Android's alarm clock and Management 2010-06-21

    android alarm clock Mobile Development 2009-08-19 09:42:41 read 194 comments 0 font size: large, medium Android recently looked at the alarm clock and Management (AlarmManager), I really do not mistake, powerful and simple, the code is as follows: 1,

  • ADROID 2.1 Analytical framework 6 Alarm Clock 2010-12-05

    6 Alarm Clock 6.1 set timer time file: packages / apps / alarmclock / src / com / android / alarmclock / Alarms.java private static void enableAlert (Context context, final Alarm alarm, final long atTimeInMillis) { AlarmManager am = (AlarmManager) co

  • Upper Android Application - Alarm Clock 2011-03-18

    Recently new to the Android operating system, I completed the set of questions is: Android upper layer application - electronic alarm clock. Because the contact time is not long to catch a practice, so this is not very understanding, it is because so

  • Centos 6.5 安装 chrome , mplayer , alarm , clock 2014-08-26

    Chrome wget http://chrome.richardlloyd.org.uk/install_chrome.sh chmod u+x install_chrome.sh ./install_chrome.sh NTFS yum -y install ntfs-3g Virtualbox yum -y install kernel-devel Mplayer yum -y install svn yum -y install wget yum -y install yasm yum

  • C # winform small alarm clock 2011-05-11

    Busy recently, teachers forget something at the computer all day, so in order to remind myself to be a C # winform program and thought the hand of it! I realized the alarm function is relatively simple, mainly used in the timer control, timer, and al

  • PendingIntent and AlarmManager Introduction 2010-05-05

    Transfer from: http://dev.chinamobile.com/cmdn/bbs/thread-9526-1-1.html SUMMARY: Based on the OPhone built-in alarm function briefly to allow developers to friends understanding OPhone platform based on client / server programming model, and how to u

  • android alarm settings 2011-01-07

    In the Android can be achieved by AlarmManager alarm, AlarmManager class is designed to set a specified time to complete specific events. AlarmManager provides access to the system alerts the service, set in the program as long as the alert service,

  • Own set of information packages to facilitate the updating and use of alarm start service 2010-04-22

    <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "org.moo.android.myApp" android: versionCode = "12" android: versionName = "1.2.37"> try ( PackageManager manager = context.get

  • In-depth study of AlarmManager android 2010-11-01

    Corresponds to a AlarmManagerServie AlarmManage service program, the service program is to provide an alarm service are true, it is mainly to maintain the application up and down the various types of alarm settings in a timely manner will trigger the

  • AlarmManager研究 2013-08-02

    AlarmManager研究 侯 亮 1.概述 在Android系统中,闹钟和唤醒功能都是由Alarm Manager Service控制并管理的.我们所熟悉的RTC闹钟以及定时器都和它有莫大的关系.为了便于称呼,我常常也把这个service简称为ALMS. 另外,ALMS还提供了一个AlarmManager辅助类.在实际的代码中,应用程序一般都是通过这个辅助类来和ALMS打交道的.就代码而言,辅助类只不过是把一些逻辑语义传递给ALMS服务端而已,具体怎么做则完全要看ALMS的实现代码了. AL

  • 自己动手写一个Alarm 2014-06-23

    Alarm结构的设计 应该有一个字段来存储触发时间,这个时间对于重复日也是固定的: 对于重复日,要有一个weekday的数组来存储一周内重复的星期: 将触发时间与重复日组合成一个触发时间队列,每到期一个时间,将该时间出队,再设置下一次定时任务. 触发时间的计算步骤 如果不重复,则执行2,否则到3: 则根据用户设置的触发小时和分,结合当天日期计算出完整的触发时间,判断该时间是否已经过期(与当前时间戳比较)如果过期,则加一天: 取出重复日的最后一天,计算出改天的触发时间,如果未过期,则计算出所有的触

  • linux signal processing (signal and alarm) 2010-05-12

    Simple procedures: #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<signal.h> void handle() { printf("I am steven\n"); alarm(1); } int main() { signal(SIGALRM,handle); alarm(3); while(1){} return 0; } Func

  • Small clock with searchlight 2010-05-27

    Today, the little clock in the night mode, add the spotlight, completed my third computer graphics work. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using Sy

  • WARNING: Clock skew detected. Your build may be incomplete. 2010-09-15

    Reprinted http://hi.baidu.com/baseetoo/blog/item/749300029bf75d7d3912bbef.html This warning is when I compile APACHE2 encountered. Before I changed the system date and time, leading to the current time and the system kernel system time inconsistency.

  • Android examples of common functions such as the IMEI number 2010-07-14

    Android screen display settings Program is of a silent display of title bar and system tray, sometimes it affect the program interface is very beautiful. The default is the vertical screen mobile phone, or status associated with the sensors, to a cer

  • Instances of common functions Android ----( k) small feature (for IMEI | phone number, etc.) 2010-12-03

    Android screen display settings Program is of a silent display of system information column title bar and, sometimes, this is the beauty of the program interface. The default is the vertical screen mobile phone, or status associated with the sensors,

  • Some common events android 2011-05-27

    1: see if there is a memory card inserted String status = Environment.getExternalStorageState (); if (status.equals (Enviroment.MEDIA_MOUNTED)) { Help with SD card inserted } 2: Let a transparent Activity OnCreate is not set Layout this.setTheme (R.s

  • Android broadcast event handling Broadcast Receiver 2010-11-05

    A. Broadcast Receive the radio receiver, and event handling mechanism is similar, but the event handling mechanism is the program component level, and broadcast processing mechanism is a system level. II. Events broadcast parity is simple, build Inte

  • SystemClock.sleep and the difference between Thread.sleep 2011-05-24

    In Java, when we deal with thread synchronization problems, processing delays may use the Thread class sleep methods, where some of the ways aside concurrent class, in fact, Android platform also provides a SystemClock.sleep methods, they have what i