AlarmManager, a system service provided by Android)

Source: Internet
Author: User

AlarmManager, a system service provided by Android)

 

 

This section introduces:

This section describes AlarmManager In the Android system service ),

In addition to the development of mobile phone alarm clocks, it is more often used as a global timer, usually with the Service

Start other components at a specific time! This section describes the AlarmManager.

At the same time, the usage of AlarmManager is demonstrated through the small alarm clock and automatic wallpaper change.

Content!

 

Body of this section:

1. concept and related attribute method diagram:

 

 

2. Demo

Well, you can't do it without training. Here are two simple examples:

They are the implementation of scheduled alarm reminders and the regular replacement of mobile phone wallpapers. One is to call Activity, and the other is to call Service

 

① A simple alarm:

MainActivity. java:

 

Package com. jay. example. alarmmanagerdemo; import java. util. calendar; import android. app. activity; import android. app. alarmManager; import android. app. pendingIntent; import android. app. timePickerDialog; import android. app. timePickerDialog. onTimeSetListener; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; I Mport android. widget. timePicker; import android. widget. toast; public class MainActivity extends Activity {private Button btnSetClock; private Button btnbtnCloseClock; private AlarmManager alarmManager; private PendingIntent pi; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); btnSetClock = (Button) findViewById (R. id. bt NSetClock); btnbtnCloseClock = (Button) findViewById (R. id. btnCloseClock); // ① obtain the AlarmManager object: alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE); // specify the Activity component to be started, call getActivity through PendingIntent to set Intent intent = new Intent (MainActivity. this, ClockActivity. class); pi = PendingIntent. getActivity (MainActivity. this, 0, intent, 0); btnSetClock. setOnClickListener (new OnClickListener () {@ Overrid Epublic void onClick (View v) {Calendar currentTime = Calendar. getInstance (); // A Time Setting dialog box is displayed for you to select the new TimePickerDialog (MainActivity. this, 0, new OnTimeSetListener () {@ Overridepublic void onTimeSet (TimePicker view, int hourOfDay, int minute) {// set the current time to Calendar c = Calendar. getInstance (); c. setTimeInMillis (System. currentTimeMillis (); // sets the Calendar Object Based on the time selected by the user. set (Calendar. HOUR, hourOfDay); c. set (Calend Ar. MINUTE, minute); // ② set the time when AlarmManager starts ActivityalarmManager in the Calendar. set (AlarmManager. RTC_WAKEUP, c. getTimeInMillis (), pi); // you are prompted to set the alarm: Toast. makeText (MainActivity. this: the alarm is set ~, Toast. LENGTH_SHORT ). show () ;}, currentTime. get (Calendar. HOUR_OF_DAY), currentTime. get (Calendar. MINUTE), false ). show (); btnbtnCloseClock. setVisibility (View. VISIBLE) ;}}); btnbtnCloseClock. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {alarmManager. cancel (pi); btnbtnCloseClock. setVisibility (View. GONE); Toast. makeText (MainActivity. this, the alarm is canceled, Toast. LENGTH_SHORT ). show ();}});}}


 

ClockActivity. java:

 

Package com. jay. example. alarmmanagerdemo; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. content. dialogInterface. onClickListener; import android. media. mediaPlayer; import android. OS. bundle; public class ClockActivity extends Activity {private MediaPlayer mediaPlayer; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. oncres Ate (savedInstanceState); setContentView (R. layout. activity_clock); mediaPlayer = MediaPlayer. create (this, R. raw. pig); // mediaPlayer. setLooping (true); mediaPlayer. start (); // create an alert dialog box. Click OK to close the alert and the new AlertDialog page. builder (ClockActivity. this ). setTitle (Alarm ). setMessage (Piglet gets up quickly ~). SetPositiveButton (disable the alarm, new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {mediaPlayer. stop (); ClockActivity. this. finish ();}}). show ();}}

!!! Also, do not forget to register ClockActivity in AndroidManifest. xml!

 

 

Run:

 

Summarize the core process:

① AlarmManager alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE );

Obtain the AlarmManager service objects provided by the system.

② Intent:

Intent intent = new Intent (MainActivity. this, ClockActivity. class );

③ Set the PendingIntent object to start Activity, Service, or broadcast!

PendingIntent pi = PendingIntent. getActivity (MainActivity. this, 0, intent, 0 );

④ Call the set () method of AlarmManager to set the alarm type, start time, And PendingIntent object of a single alarm!

AlarmManager. set (AlarmManager. RTC_WAKEUP, c. getTimeInMillis (), pi );

 

 

 

 

 

② Regular wallpaper change for background Service:

From the code above, we found that the usage of AlarmManager is actually a few steps, which is very simple. Next we will get a Service

Here we involve another API:WallpaperManagerTo manage the wallpaper, the following methods are provided for our use:

SetBitmap (Bitmap bitmap), setResource (int resid), setStream (InputStream data );

There is also a clear WallpaperCleanMethod!

 

The process is similar to the previous alarm clock principle, so I will not explain it. paste the Code directly:

Activity_main.xml:

 

 
  
  
  
 

Next, go to MainActivity. java:

 

 

Package com. example. alarmmanagerdemo2; import java. io. IOException; import android. app. activity; import android. app. alarmManager; import android. app. pendingIntent; import android. app. wallpaperManager; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity ext Ends Activity {private Button btnOn; private Button btnOff; private Button btnCancel; private AlarmManager alarmManager; private PendingIntent pi; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // ① obtain the AlarmManager object: alarmManager = (AlarmManager) getSystemService (ALARM_SERVICE); // ② specify the Service to be started and specify that the action is Servce: Intent int Ent = new Intent (MainActivity. this, WallPagerService. class); pi = PendingIntent. getService (MainActivity. this, 0, intent, 0); btnOn = (Button) findViewById (R. id. btnOn); btnOff = (Button) findViewById (R. id. btnOff); btnCancel = (Button) findViewById (R. id. btnCancel); btnOn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {alarmManager. setRepeating (AlarmManager. RTC_WAKEUP, 0, 30 00, pi); btnOn. setEnabled (false); btnOff. setEnabled (true); Toast. makeText (MainActivity. this, the wallpaper is automatically changed and set to Toast. LENGTH_SHORT ). show () ;}}); btnOff. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {btnOn. setEnabled (true); btnOff. setEnabled (false); alarmManager. cancel (pi) ;}}); btnCancel. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {try {Wallpaper Manager. getInstance (getApplicationContext (). clear (); Toast. makeText (MainActivity. this, the wallpaper is successfully cleared ~, Toast. LENGTH_SHORT). show () ;}catch (IOException e) {e. printStackTrace ();}}});}}

There is also our custom wallpaper change Service:

 

 

Package com. example. alarmmanagerdemo2; import android. app. service; import android. app. wallpaperManager; import android. content. intent; import android. OS. IBinder; public class WallPagerService extends Service {// defines the current wallpaper. The following table int current = 0; // gets the wallpaper resource id array private int [] paper = new int [] {R. drawable. gui_1, R. drawable. gui_2, R. drawable. gui_3, R. drawable. gui_4,}; // defines the WallpaperManager service private WallpaperManager wManager; // initializes the WallPagerManager @ Overridepublic void onCreate () {super. onCreate (); wManager = WallpaperManager. getInstance (this) ;}@ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {if (current> = 4) current = 0; try {wManager. setResource (paper [current ++]);} catch (Exception e) {e. printStackTrace () ;}return START_STICKY ;}@ Overridepublic IBinder onBind (Intent intent) {return null ;}}

Don't forget to add the wallpaper permission to the AndroidManifest. xml file! And register for our Service !!!

 

 

 


 

Run:

 

 

 

 

The last two sentences are as follows:

It's that simple. Learn about AlarmManager (alarm clock Service) here. We will explain it in the Service instance later.

In the background, we will also provide an example of regularly sending text messages ~

 

 

 

 

 

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.