My Android advanced tour ------ & gt; Android uses the AlarmManager global timer to implement regular wallpaper replacement, androidalarmmanager

Source: Internet
Author: User

My Android advanced tour ------> Android uses AlarmManager global timer to implement regular wallpaper replacement, androidalarmmanager


The DEMO periodically calls ChangeService through AlarmManager, so that the system can change the wallpaper at regular intervals.

Android. app. WallpaperManager provides the clear () method to clear the wallpaper and the following method to set the wallpaper.

SetResource (int resid): Set the wallpaper to the image represented by the resid resource.

SetBitmap (Bitmap bitmap) sets the wallpaper as a bitmap.

SetStream (InputStream data) sets the wallpaper as the image represented by data



In Android, AlarmManager is essentially a global timer. It is a system-level prompt Service commonly used in Android. It starts other components (including Activity, Service, BroadcastReceiver) at a specified time or periodically ).

I. Overview:

This class provides a way to access the system alarm service, allowing you to set up to execute your application at a certain time point in the future. When your alarm goes off (Time is up), an Intent registered on it will be broadcast by the system and then automatically start the target program, if it is not running. Registered alarms are retained even if the device is in sleep state (you can choose whether to wake up the device at a given time ). If the alarm is disabled or restarted, the alarm is cleared.

As long as the broadcast onReceive () method is being executed, the alarm Manager (AlarmManager) will hold a CPU wake-up lock to ensure that the phone will not sleep until the broadcast is completed, once onReceive () then the alarm manager will release the wake-up lock. This means that as long as the OnReceive () method is complete, your mobile phone may enter sleep in some cases. If your alarm notification Receiver calls Context. startService (), the mobile phone may enter sleep before the requested service is executed. To prevent this situation, your BroadcastReceiver and service need to implement a separate wake-up lock policy to ensure that the mobile phone continues to run until the service is available.

Note: This class applies to scenarios where you want your application to run at a specific time point in the future, even if your application is not running now. Handler is easier and more efficient for general time operations.

2. Public Methods ):

void cancel(PendingIntent operation) 

Cancel the scheduled service of AlarmManager.


void set(inttype,longtriggerAtTime, PendingIntent operation)

Set the triggerAtTime to start the component specified by the operation parameter. (This method is used to set a one-time alarm)


void  setInexactRepeating(inttype,longtriggerAtTime,longinterval, PendingIntent operation)

Set an inaccurate periodic task.


void  setRepeating(inttype,longtriggerAtTime,longinterval, PendingIntent operation)
Set a scheduled service for periodic execution.


void  setTime(longmillis)

Set the system "wall" clock. Android. permission. SET_TIME. permission is required.


void  setTimeZone(String timeZone)
Set the default time zone of the system. Android. permission. SET_TIME_ZONE. permission is required.


Iii. Common Methods:
There are three common AlarmManager methods:


set(inttype,longstartTime,PendingIntent pi)


This method is used to set a one-time alarm.
The first parameter, int type, specifies the type of the scheduled service. The parameter accepts the following values:

ELAPSED_REALTIME: sends broadcasts after the specified delay, but does not wake up the device (the alarm clock is unavailable during sleep ). If the alarm is triggered during system sleep, it will not be passed until the next device wakes up.

ELAPSED_REALTIME_WAKEUP: after the specified delay, send a broadcast and wake up the device (the operation component is executed even if the device is shut down ).
Latency refers to the system startup time SystemClock. elapsedRealtime (). The specific usage depends on the code.

RTC: Specify the device that starts operation when the value returned by the System call System. currentTimeMillis () method is equal to triggerAtTime (send broadcast at the specified time, but do not wake up the device ). If the alarm is triggered during system sleep, it will not be passed until the next device wakes up (the alarm is unavailable during sleep ).

RTC_WAKEUP: Specify the device that starts operation when the value returned by the System call System. currentTimeMillis () method is equal to triggerAtTime (send broadcast at the specified time and wake up the device ). The operation component is executed even if the system is shut down.

The second parameter indicates the time when the alarm is executed.

The third parameter PendingIntent pi indicates the alarm response action:

PendingIntent pi: indicates the execution of an alarm, for example, sending a broadcast or giving a prompt. PendingIntent is the encapsulation class of Intent. It should be noted that if the alarm is triggered by starting the service, the PendingIntent object should be obtained using Pending. getService (Context c, int I, Intentintent, int j) method; if the alarm is triggered through broadcast, the PendingIntent object should be obtained using PendingIntent. getBroadcast (Context c, inti, Intent intent, int j) method; if the alarm is triggered by an Activity, the PendingIntent object should be obtained by PendingIntent. getActivity (Context c, inti, Intent intent, int j) method. If these three methods are used incorrectly, although no error is reported, the alarm is not displayed.


setRepeating(inttype,longstartTime,longintervalTime,PendingIntent pi)

Set a scheduled service for periodic execution. The first parameter indicates the alarm type, the second parameter indicates the first execution time of the alarm, the third parameter indicates the interval between two executions of the alarm, and the third parameter indicates the alarm response action.


setInexactRepeating(int type, long triggerAtMillis,long intervalMillis,PendingIntent operation) 

This method is also used to set repeated alarms, similar to the second method, but the interval between the two alarms is not fixed. It is relatively more power-efficient because the system may merge several similar alarms into one to reduce the number of device wake-up times. The third parameter intervalTime is the alarm interval. the built-in variables are as follows:

INTERVAL_DAY: Set the alarm interval for one day.
INTERVAL_HALF_DAY: set an alarm, with an interval of half a day
Interval_effecteen_minutes: sets the alarm time interval of 15 minutes.
INTERVAL_HALF_HOUR: set an alarm, with an interval of half an hour.
INTERVAL_HOUR: set an alarm time interval of one hour.


========================================================== ========================================================== ============================



AlarmChangeWallpaper. java

Package com. oyp. alarm. change. wallpaper; import android. OS. bundle; import android. app. activity; import android. app. alarmManager; import android. app. pendingIntent; import android. app. service; import android. content. intent; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class AlarmChangeWallpaper extends Activity {AlarmManager alarmManager; Button start, stop; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); start = (Button) findViewById (R. id. start); stop = (Button) findViewById (R. id. stop); alarmManager = (AlarmManager) getSystemService (Service. ALARM_SERVICE); // specify to start the ChangeService component Intent intent = new Intent (AlarmChangeWallpaper. this, ChangeService. class); final PendingIntent pi = PendingIntent. getService (AlarmChangeWallpaper. this, 0, intent, 0); start. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// sets the PendingIntent object pi every 5s starting from the current time, note the relationship between the first parameter and the second parameter // broadcast alarmManager through the PendingIntent pi object after 5 seconds. setRepeating (AlarmManager. RTC_WAKEUP, 0, 5000, pi); start. setEnabled (false); stop. setEnabled (true); Toast. makeText (AlarmChangeWallpaper. this, "regular wallpaper replacement succeeded", Toast. LENGTH_SHORT ). show () ;}}); stop. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {start. setEnabled (true); stop. setEnabled (false); // cancel the scheduling of pi alarmManager. cancel (pi );}});}}


ChangeService. java

Package com. oyp. alarm. change. wallpaper; import android. app. service; import android. app. wallpaperManager; import android. content. intent; import android. OS. IBinder; public class ChangeService extends Service {// defines the wallpaper resource int [] wallpapers = new int [] {R. drawable. a, R. drawable. b, R. drawable. c, R. drawable. d}; // define the system's wallpaper Management Service WallpaperManager wallpaperManager; // define the currently displayed wallpaper int current = 0; @ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// if the last one is reached, restart if (current> = wallpapers. length) {current = 0;} try {// change wallpaper wallpaperManager. setResource (wallpapers [current ++]);} catch (Exception e) {e. printStackTrace ();} return START_STICKY;} @ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); // initialize WallpaperManagerwallpaperManager = WallpaperManager. getInstance (this) ;}@ Overridepublic IBinder onBind (Intent intent) {// TODO Auto-generated method stubreturn null ;}}


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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".AlarmChangeWallpaper" >    <Button        android:id="@+id/start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Start" />        <Button        android:id="@+id/stop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Stop" /></LinearLayout>




AndroidManifest. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "com. oyp. alarm. change. wallpaper "android: versionCode =" 1 "android: versionName =" 1.0 "> <uses-sdk android: minSdkVersion =" 8 "android: targetSdkVersion =" 18 "/> <! -- Grant the user the permission to modify the wallpaper --> <uses-permission android: name = "android. permission. SET_WALLPAPER "/> <application android: allowBackup =" true "android: icon =" @ drawable/c "android: label =" @ string/app_name "android: theme = "@ style/AppTheme"> <activity android: name = "com. oyp. alarm. change. wallpaper. alarmChangeWallpaper "android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <Category android: name = "android. intent. category. LAUNCHER"/> </intent-filter> </activity> <! -- Register ChangeService --> <service android: name = ". ChangeService"/> </application> </manifest>



PS: see the link below.

Http://blog.csdn.net/fengyuzhengfan/article/details/38417935? Utm_source = tuicool

Mainly implemented:

1. Use AssetManager to copy files in the assets Directory to the specified location on the SD card.

2. Use the global timer of AlarmManager to periodically start the specified component to switch the wallpaper.

3. Use SharedPreferences to save personalized settings to your mobile phone (for example, wallpaper switching frequency)

4. Use custom title bars

5. The GestureDetector gesture detector is used to allow the user to slide the screen.

6. overridePendingTransition is used, which has an animation effect when the screen is switched.



========================================================== ========================================================== ============================

Author: Ouyang Peng: Welcome to repost. sharing with others is the source of progress!

Reprinted Please retain the original address: http://blog.csdn.net/ouyang_peng

========================================================== ========================================================== ============================

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.