Introduction to intent and pendingintent in combination with alarmmanager for Android

Source: Internet
Author: User

First, let's briefly talk about the mechanism of alarmmanager: Global timer (also called alarm clock), which broadcasts a specified intent for us at a specific time in two forms:

1. execute an operation when the specified time arrives. If you have set an alarm time, when the time arrives, alarmmanager broadcasts a preset intent for us, use this intent to perform some operations [actually pendingintent]

2. Periodically execute an operation at a specified interval.

 

Alarmmanager Alarm types and methods:

The Android system provides four types of alarms:

(1) elapsed_realtime: Send intent after the specified delay, but do not wake up the device

(2) elapsed_realtime_wakeup: Send intent after the specified delay and wake up the device

Latency is to calculate the system startup time systemclock. elapsedrealtime !!

(3) RTC: Send intent at the specified time, but do not wake up the device

(4) rtc_wakeup: Send intent at the specified time and wake up the device

 

Alarmmanager method:

(1) void set (INT type, long triggerattime, pendingintent Operation)
Register an alert clock

(2) void setrepeating (INT type, long triggerattime, long interval, pendingintent Operation)
Register an alarm that will be repeated

(3) void setinexactrepeating (INT type, long triggerattime, long interval, pendingintent Operation)
Register an inaccurate version of the duplicate alarm, which is relatively more energy-efficient, because the system may merge several similar alarms into one for execution, this reduces the number of device wakeup times.
Built-in interval:
Interval_effecteen_minutes
Interval_half_hour
Interval_hour
Interval_half_day
Interval_day
If you set it to day, all the alarms on the day may be merged.

(4) void cancel (pendingintent Operation)
Cancel a registered alarm clock

(5) void settimezone (string timezone)
Set the default time zone of the system. Android. Permission. set_time_zone permission is required

 

(5 ),VoidSettime(Long millis)

Set the system clock time. Android. Permission. set_time permission is required.

 

The following is the question:

Relationship between intent and pendingintent:

Intent is an intent that describes the intention to start an activity, broadcast, or service. The main information it holds is the component (activity, broadcast, or service) it wants to start. In development operations, you need to use startactivity, startservice or sendbroadcast method to start this intent to execute some operations !!

Pendingintent can be considered as the packaging of intent. In fact, it is used by the current app or other apps, and is commonly used by external apps. When an external app executes this pendingintent, indirectly call the intent, that is, the external app delays the execution of the intent described in pendingintent and its final behavior. The pendingintent mainly holds the information of its packaged intent and the current app context, even if the current app does not exist, you can execute intent through context in pendingintent. When you submit pendingintent to another program for processing, pendingintent still has the permissions of the original pendingintent program. When you get a pendingintent from the system, you must be very careful. For example, generally, if the intent destination is your own component (activity/service/broadcastreceiver), You 'd better display the specified component name in the intent, to ensure that the intent can reach the destination, otherwise the intent may not know where to send it.

It can be understood as follows: when you want to start another bactivity in Aactivity, you can select either immediate start or delayed start in two cases:
1. Configure the bactivity to be started through intent, and then call the startactivity () method, so that he can immediately perform the start operation and jump to the past.
2. in another case, although you want to start another bactivity, you do not want to jump to the bactivity page immediately. You want to wait for 5 minutes and then jump to the bactivity, you can use pendingintent to implement [of course there are many implementation methods. Here we only want to explain the difference between pendingintent and intent]. pendingintent can wrap intent in step 1, then, through the alarmmanager timer, We can customize the pendingintent five minutes later to implement this delayed operation. If you still seem to be confused and confused, I mean it is very stressful, what should I do to make it clear? After all, the theory is abstract. Later I will explain it through a program. In the program, I started a broadcastreceiver. In fact, the principle is the same !!

How to obtain a pendingintent? It is actually very simple:
1. You can use the getactivity (context, int requestcode, intent, int flags) series of methods from the system

Obtains a pendingintent object used to start an activity.
2. You can use the getservice (context, int requestcode, intent, int flags) method to obtain

Pendingintent object used to start a service
3. You can use the getbroadcast (context, int requestcode, intent, int flags) method to obtain

Pendingintent objects used to send broadcasts to broadcastreceiver

Pendingintent constants:

1. flag_cancel_current: If the pendingintent managed by alarmmanager already exists, the current

Pendingintent to create a new pendingintent
2. flag_update_current: If the pendingintent managed by alarmmanager already exists, before updating the new intent

Intent object data in pendingintent, such as updating extras in intent. In addition, we can also

Call pendingintent's cancel () to remove it from the system
3. flag_no_create: If the pendingintent managed by alarmmanager already exists, no operation will be performed and

Pendingintent. If pendingintent does not exist, null is returned.

 

Code pasting:

1. mainactivity. Java:

Package COM. test. alarm; import COM. test. alarm. r; import android. app. activity; import android. app. alarmmanager; import android. app. pendingintent; import android. content. context; import android. content. intent; import android. OS. bundle; import android. OS. systemclock; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. textview; public class mainactivity extends activity {private button msetbutton; private button mcancelbutton; private textview mtextview; private final int request_code_0 = 0; private final int request_code_1 = 1; /** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); mtextview = (textview) This. findviewbyid (R. id. mtext); msetbutton = (button) This. findviewbyid (R. id. settimebutton); mcancelbutton = (button) findviewbyid (R. id. cancelbutton); msetbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {alarmmanager alarmmgr = (alarmmanager) getsystemservice (context. alarm_service); intent = new intent (getapplicationcontext (), alermreceiver. class); intent. putextra ("flag", true); // create two pendingintentpendingintent setpendintent0 = pendingintent. getbroadcast (getapplicationcontext (), request_code_0, intent, pendingintent. flag_update_current); log. E ("flag_update_current --> setpendintent0:", setpendintent0 + ""); pendingintent setpendintent1 = pendingintent. getbroadcast (getapplicationcontext (), request_code_1, intent, pendingintent. flag_update_current); log. E ("flag_update_current --> setpendintent1:", setpendintent1 + ""); // send broadcast after 5 seconds, and then broadcast int triggerattime = (INT) (systemclock every 10 seconds. elapsedrealtime () + 5*1000); int interval = 10*1000; // register the two pendingintents created above and broadcast alarmmgr again every 10 seconds. setrepeating (alarmmanager. elapsed_realtime_wakeup, triggerattime, interval, setpendintent0); alarmmgr. setrepeating (alarmmanager. elapsed_realtime_wakeup, triggerattime, interval, setpendintent1); // alarmmgr. set (alarmmanager. elapsed_realtime_wakeup, // triggerattime, pendintent1) ;}}; mcancelbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {alarmmanager alarmmgr = (alarmmanager) getsystemservice (context. alarm_service); intent = new intent (getapplicationcontext (), alermreceiver. class); intent. putextra ("flag", false); pendingintent stoppendintent0 = pendingintent. getbroadcast (getapplicationcontext (), request_code_0, intent, pendingintent. flag_update_current);/*** if you want to update the flag value in putextra to false, you must register it again using the setxxx () method of alarmmgr, * It is equivalent to updating an existing intent. If you do not do this, you will not be able to achieve the purpose of updating, like this: ** alarmmgr. set (alarmmanager. elapsed_realtime_wakeup, 0, * stoppendintent0); ** then you execute alarmmgr. cancel (stoppendintent0); cancel ** this may be because you started an alarm with the flag and set a bell, I also want to use flag to close the alarm but I cannot close it at all. * The problem may be here because you have not actually updated the data * // alarmmgr. set (alarmmanager. elapsed_realtime_wakeup, 0, // stoppendintent0); log. E ("flag_update_current --> stoppendintent0:", stoppendintent0 + ""); alarmmgr. cancel (stoppendintent0); // The following is only to demonstrate the differences between several constants of pendingintent: pendingintent stoppendintent1 = pendingintent. getbroadcast (getapplicationcontext (), request_code_1, intent, pendingintent. flag_update_current); log. E ("flag_update_current --> stoppendintent1:", stoppendintent1 + ""); alarmmgr. cancel (stoppendintent1); pendingintent stoppendintent11 = pendingintent. getbroadcast (getapplicationcontext (), request_code_1, intent, pendingintent. flag_no_create); log. E ("flag_no_create -------> stoppendintent11:", stoppendintent11 + ""); alarmmgr. cancel (stoppendintent11); pendingintent stoppendintent12 = pendingintent. getbroadcast (getapplicationcontext (), request_code_1, intent, pendingintent. flag_cancel_current); log. E ("flag_cancel_current --> stoppendintent12:", stoppendintent12 + ""); alarmmgr. cancel (stoppendintent12); pendingintent stoppendintent13 = pendingintent. getbroadcast (getapplicationcontext (), request_code_1, intent, pendingintent. flag_one_shot); log. E ("flag_one_shot --------> stoppendintent13:", stoppendintent13 + ""); alarmmgr. cancel (stoppendintent13 );}});}}

2. Broadcast listening:

Package COM. test. alarm; import android. content. broadcastreceiver; import android. content. context; import android. content. intent; import android. OS. bundle; import android. util. log; import android. widget. toast; public class alermreceiver extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {bundle = intent. getextras (); toast. maketext (context, "Go to the alarm clock broadcastreceiver ", 100). Show (); If (bundle! = NULL) {log. I ("alermreceiver:", String. valueof (bundle. getboolean ("flag"); If (bundle. getboolean ("flag") {// enable toast. maketext (context, "enabled", 100 ). show ();} else {// turn off the alarm toast. maketext (context, "disabled", 100 ). show ();}}}}

3. activity_main.xml on the home page:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/mText"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />    <Button        android:id="@+id/setTimeButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/setTimeButton" />    <Button        android:id="@+id/cancelButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/cancelButton" /></LinearLayout>

 

Do not forget to register broadcast in androidmanifest. xml.

<Cycler Android: Name = "com. Test. Alarm. alermreceiver"/>

 

Run:

 

By printing the log, we can see the Approximate differences between the pendingintent constants !!

 

 

 

 

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.