Android Essay--The Alarmmanager of the alarm clock making

Source: Internet
Author: User

To tell the truth, previously written two blog android broadcast mechanism broadcast detailed ,android time, date related classes and methods and now to write, is to write the alarm clock application to do bedding, interested, we can go to see the top two blog.

I. Introduction of Alarmmanager

For an application of the alarm clock implementation, the personal feel that the most important should belong to the Alarmmanager. Alarmmanager, called the global timer, literally means the alarm clock management (forgive my crappy English), is a system-level prompt service commonly used in Android, and broadcasts a specified intent for us at certain moments. Simply put, we set a time, and then when the time comes, Alarmmanager for us to broadcast a intent we set, usually we use pendingintent (this goods in the call system to send text messages when also have, find a time to review the intent, Incidentally, this is also a good study), pendingintent can be understood as intent package, simply said in intent on the addition of a specified action. When using intent, we also need to perform startactivity, StartService, or sendbroadcast to make intent useful. And Pendingintent's words are to include this action inside.

Define a Pendingintent object, here to draw the same gourd, the next time to learn to speak pendingintent pi = pendingintent.getbroadcast (Context, int, Intent, int);

Ii. Introduction to common methods of Alarmmanager

The common methods provided by the Alarmmanager class are mainly a few:

 Public voidSetintTypeLongTriggeratmillis, pendingintent operation) function: used to set a one-time alarm, the first parameter represents the alarm type, the second parameter indicates how long it will take to wait for the alarm to be triggered, which is related to type (do not know English. I also check to understand the meaning of this parameter),
Action parameters for the third parameter alarm response: Type:AlarmManager.ELAPSED_REALTIME indicates that the alarm is not available in the sleep state of the phone, the alarm is used relative time (relative to the start of system boot), the status value is 3; alarmma Nager. Elapsed_realtime_wakeup means that the alarm will wake up the system and perform the prompt function when it sleeps, the alarm is also used relative time, the status value is 2, ALARMMANAGER.RTC means the alarm is not available in sleep, the alarm is used in the state. Absolute time, that is, the current system time, the status value is 1, alarmmanager.rtc_wakeup means that the alarm will wake up the system and perform the prompt function, the alarm is used absolute time, the status value is 0; alarmmanager . Power_off_wakeup means that the alarm clock in the state of the hand machine can also be a normal prompt function, the state of the alarm clock is also used absolute time, the status of 4; But I didn't test it.
This constant, estimated and SDK about operation bound the execution of the alarm clock, such as sending a broadcast, giving hints and so on. Public voidSetexact (intTypeLongTriggeratmillis, pendingintent operation) function: In the specified time, the precise execution of the alarm clock, this function should be the alarm clock execution accuracy is relatively high bar Public voidSetrepeating (intTypeLongTriggeratmills,LongIntervalmillis, pendingintent operation) Function: This method is used to set the repetition alarm, the first parameter represents the alarm type, the second parameter indicates the time to wait for the alarm to be triggered, and the third parameter indicates the time interval between two executions of the alarm. The third parameter represents an alarm response action. Public voidSetinexactrepeating (intTypeLongTriggeratmills,LongIntervalmillis, pendingintent operation) function: set an imprecise version of a repeating alarm, which is relatively more energy efficient, because the system may combine several similar alarms into one to execute, reducing the number of wake-up times of the device. Because it's not the exact version, so here's Intervamills
will have slightly different parameters: Intervalmillis:interval_fifteen_minutes interval_half_hour Interval_hour Interval_half_day Interval_day Public voidCancel (Pendingintent operation) function: Cancels a set of alarms and removes any alarm that matches the intent Public voidSettimezone (String timeZone) feature: Sets the default time zone for the system. Requires Android.permission.SET_TIME_ZONE permissions

A city A simple example of an alarm clock demo

First of all, we now register a broadcast in the Androidmanifest.xml, if not clear can go to see I wrote before the blog Android essay--android broadcasting mechanism broadcast detailed

<receiverAndroid:name=". Alarmreceiver " ><!--reveiver Name, if the internal class statically registers the broadcast, add $ before the inner class -            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.ALARM_RECEIVER" /><!--broadcast received by intent -                <categoryAndroid:name= "Android.intent.category.DEFAULT" />            </Intent-filter>        </receiver>

Next, we will write a broadcast receiver, to receive the alarm broadcast events, and related processing

1  PackageCom.example.alarmmanager;2 3 ImportAndroid.content.BroadcastReceiver;4 ImportAndroid.content.Context;5 Importandroid.content.Intent;6 ImportAndroid.widget.Toast;7 8  Public classAlarmreceiverextendsbroadcastreceiver{9 Ten @Override One      Public voidonreceive (Context arg0, Intent arg1) { A         //Here you can add alarm tones -System.out.println ("I am the alarm clock, I want to wake you ..."); -Toast.maketext (arg0, "I am the alarm clock, I want to wake you ...", Toast.length_short). Show ();  the     } -  -}

Finally, write the specific implementation code in Mainactivity.java.

1  PackageCom.example.alarmmanager;2 3 Importandroid.app.Activity;4 ImportAndroid.app.AlarmManager;5 Importandroid.app.PendingIntent;6 Importandroid.content.Intent;7 ImportAndroid.os.Bundle;8 ImportAndroid.view.View;9 ImportAndroid.view.View.OnClickListener;Ten  One  Public classMainactivityextendsActivityImplementsOnclicklistener { A  -     PrivateAlarmmanager Alarmmanager; -     Privatependingintent operation; the  -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); +  -         //Initialize the button and bind the Listener event +Findviewbyid (R.id.clock). Setonclicklistener ( This); AFindviewbyid (R.id.repeating_clock). Setonclicklistener ( This); atFindviewbyid (R.id.cancel_clock). Setonclicklistener ( This); -  -         //Get Alarmmanager Object -Alarmmanager =(Alarmmanager) Getsystemservice (alarm_service); -  -         //create Intent object, action is Android.intent.action.ALARM_RECEIVER inIntent Intent =NewIntent ("Android.intent.action.ALARM_RECEIVER"); -Operation = Pendingintent.getbroadcast ( This, 0, intent, 0); to     } +  - @Override the      Public voidOnClick (View v) { *         Switch(V.getid ()) { $          CaseR.id.clock://set a disposable alarmPanax NotoginsengAlarmmanager.set (Alarmmanager.rtc_wakeup, 10000, operation); -              Break; the          CaseR.id.repeating_clock://set a repeating alarm +Alarmmanager.setrepeating (Alarmmanager.rtc_wakeup, 5000, 10000, A operation); the              Break; +          CaseR.id.cancel_clock://Cancel Alarm - Alarmmanager.cancel (operation); $              Break; $         default: -              Break; -         } the     } -}

Activity_main.xml

<LinearLayoutxmlns: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" >    <ButtonAndroid:id= "@+id/clock"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Set one-time alarm" />    <ButtonAndroid:id= "@+id/repeating_clock"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Set repeating alarm" />    <ButtonAndroid:id= "@+id/cancel_clock"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Cancel Alarm" /></LinearLayout>

In this way, a simple alarm clock is finished, call ~ My goal is to do a real can use the alarm clock, and make unremitting efforts! You are also welcome to pay attention to my blog!

Author: Sky Road

Reprint please indicate source: http://www.cnblogs.com/travellife/

SOURCE download: Baidu Cloud Disk

Android Essay--The Alarmmanager of the alarm clock making

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.