Android official article Translation Management device wake-up status (Managing Device Awake State)

Source: Internet
Author: User

These months have been learning iOS development, put Android aside for a long time, it is time to know the new.

Say a little off, these days in the developer of the official documents, about material design and understand a bit.

Material early in 2014, the Googleio Congress has been launched by Google, but the market to adopt this new design program of the app is very few, the foreign follow soon, the domestic almost no progress, looking at the domestic major companies mobile apps, rarely "with The Times" Design of the new system introduced by Google.

However, this is a long-standing reason, because the Android version is too fragmented, the major mobile phone brands are also each battalion, the use of their own custom UI interface, which led to if you want to use Google's design to redesign your app, will lead to your program, from the icon to the user interface, may be out of tune with the user's phone, so most of the company's apps have adopted a "universal" design, the general main tone is the color of their own brand, such as the popular reviews of the orange color tones, such as the blue tone of the group.

Therefore, it is often difficult for programmers to apply new technology to the program. If you want to learn new technology and application, you can only write a small demo, if you are very lazy, that probably so far, have not written material design style of the program it! I would think this is a pity, because this way, you will become less than the evolution of Android, Many API changes will take you by surprise. In fact, I also belong to the ranks of regret, since learning iOS, there is little attention. Recently re-review, found that the system has a lot to let you look at the very vacant API methods and techniques, a lot of method name or skill, design patterns and other similar to iOS, such as the material design is now more called tint color properties, to set the status bar color, etc. The tint color in navigation bar in this iOS is similar.

In a word, do not forget and stop learning, because we are engaged in technology. ^_^

。。。 Feel not into the subject will run off, first don't say, write today's content.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////

When your device is idle, it will first darken the screen, then turn off the mask (that is, the black screen, you have to press the power key and so on to re-charge it), will eventually turn off the phone's CPU, the purpose is to prevent the device's battery quickly exhausted, but many times, your program may request some unusual behavior, Need to keep your phone "running", not black screen.

1. Programs such as games or video classes will want to keep the screen lit.

2. Other programs may not require a screen to be lit, but they still need to keep the CPU working for them until an urgent task is completed.

This lesson describes how to keep the device awake when needed without draining the battery.

Course:

1. Keep the device awake

Learn how to keep your screen or CPU awake and minimize the impact on battery life.

2. Perform repetitive alarms (reminders)

Learn how to use duplicate reminders to perform operations that are outside the application life cycle, even if the program is not running or the device is dormant.

1. Keep the unit awake (keeping the device awake)

To avoid draining the battery, the Android device makes itself quickly idle and in a state of sleep. However, there will be scenarios that require the program to wake the screen or CPU, and then maintain that state until certain tasks are completed.

The method you use should be based on the needs of your own program, however, the general rule of thumb is that you should use the lightest possible method to minimize your program consumption system resources, and the next section describes how to handle the situation where your device's default sleep behavior is related to your program's needs ( That is, the need to keep the screen awake and require the CPU to work for you) is incompatible.

Keep the screen solid (Keep the screens on)

Some programs need to keep the screen lit, such as a game or player program, the best way is to use flag_keep_screen_on in your activity (only in activity, not in service services or other program components), for example:

@Override

Protectedvoid (savedinstancestate superoncreatesavedinstancestate);

(..);

(). (. . );

}

...

The advantage of this approach is that it is not like a wake-up lock (which is discussed in "Keeping the CPU open" below), it does not need to request special permissions, and the system can properly manage the user switching between different applications, and your program does not have to worry about releasing unused resources.

Another way to implement this is to use the Android:keepscreenon property in your program's layout file:

=android:layout_width "Match_parent"

Android:layout_height "Match_parent"

Android:keepscreenon "true" >

...

</RelativeLayout>

Using android:keepscreenon= "true" is equivalent to using flag_keep_screen_on, and you can set it in any way that best suits your program. The advantage of setting flag in your activity is that it allows you to selectively clear the flag at a later time to allow the screen to turn off the behavior.

Note: You do not need to clear flag_keep_screen_on this FLAG unless you no longer want the screen to remain in your running program (for example, if you want the screen to time out after a period of inactivity). The window manager will care about these matters and make sure that the right things happen when the program enters the background or resumes to the foreground. Use the Clearflags () method if you want to clear the flag and then run the screen to turn off again automatically.

.

Keep the CPU running (Keep the CPU on)

If you need to keep the CPU running in order to do some work before the device goes to sleep, you can use the PowerManager system service feature to wake the lock. Wake-Up Locks run your program to control the power state of the main device.

Creating and maintaining a wake-up lock can have a significant impact on the battery life of the host device, so you should use the wake-up lock when you need it strictly, and then keep it in the shortest possible time. For example, you should never use a wake-up lock in an activity, as described above, and if you want to keep the screen lit on your activity, you should use flag_keep_screen_on.

A reasonable use of a wake-up lock scenario may be in a background service where the service needs to hold this wake-up lock to ensure that the CPU is running when the screen is closed. Again, even so, this practice should be minimized due to its impact on battery life.

In order to use a wake-up lock, the first step is to add Wake_lock permissions to your program's manifest file.

=/>

If your program contains a broadcast receiver and it uses a service to perform some work, you should manage your wake-up lock through a wakefulbroadcastreceiver, which will describe how to use this method. This is one of the preferred ways. If your program doesn't follow this pattern, here's how to set up a wake-up lock directly:

PowerManager PowerManager Getsystemservicepower_service);

WakeLock powermanagernewwakelockpowermanagerpartial_wake_lock"Mywakelocktag");

Wakelock.acquire ();

Call the Wakelock.release () method to release the wake-up lock, which frees up the need for your CPU to hold. Once your program shuts down, releasing this wake-up lock is a very important step in the process, which will avoid your program's consumption of the battery.

Using Wakefulbroadcastreceiver (use Wakefulbroadcastreceiver)

Using a broadcast receiver combined with a service allows you to manage the life cycle of a background task.

A wakefulbroadcastreceiver is a special type of broadcast receiver that is responsible for creating and managing a Partial_wake_lock for your program. A wakefulbroadcastreceiver delivers work to a service (typically a intentservice) while ensuring that the device does not hibernate during the delivery process. If you do not maintain a wake-up lock while passing a task to the service, you are actually allowing the device to hibernate before the task is completed. The end result is that the application is unable to complete the task until some point in the future, which is not what you want.

The first step in using Wakefulbroadcastreceiver is to add it to your manifest, just like any other broadcast receiver:

=></receiver>

The following code starts Myintentservice with Startwakefulservice (), which is similar to Startsevice () except that Wakefulbroadcastreceiver holds a wake-up lock when the service starts. The intent of the incoming Startwakefulservice () method holds an additional information identifying this wake-up lock.

@Override

Publicvoid (Context Intent

Start the service, keeping the device awake while the service is

Launching. The Intent to deliver to the service.

Intent=newintentcontext.);

(,);

}

When the service is finished, it calls the Mywakefulreceiver.completewakefulintent () method to release the wake-up lock, and the Complewakefulintent () method has a The same intent passed in the Wakefulbroadcastreceiver as a parameter.

publicstaticfinalint=1;

Privatenotificationmanager;

Notificationcompatbuilder;

Publicmyintentservice Super "Myintentservice");

}

@Override

Protectedvoid (Intent bundle=. ();

Do the work, the requires your app to keep the CPU running.

// ...

Release the wake lock provided by the Wakefulbroadcastreceiver.

Mywakefulreceivercompletewakefulintentintent);

}

}

2. Perform repetitive alarms (reminders) (scheduling repeating Alarms)

Alarms (based on the Alarmmanager Class) give you a-to-perform time-based operations outside the lifetime of your APPL Ication. For example, the could use of a alarm to initiate a long-running operation, such as starting a service once a day to Downloa D a weather forecast.

Alarms have these characteristics:

    • They let's fire Intents at set times and/or intervals.
    • You can use the them in conjunction with broadcast receivers to start services and perform other operations.
    • They operate outside of your application, so you can use them to trigger events or actions even when your app isn't Runni Ng, and even if the device itself is asleep.
    • They help minimize your app ' s resource requirements. You can schedule operations without relying on timers or continuously running background services.

Note:for timing operations that is guaranteed to occur during the lifetime of your application, instead conside R using the Handler class in conjunction with Timer and Thread. This approach gives Android better control over system resources.

Understand the Trade-offs

A repeating alarm is a relatively simple mechanism with limited flexibility. It May is not being the best choice for your app, particularly if you need to trigger network operations. A poorly designed alarm can cause battery drain and put a significant load on servers.

A common scenario for triggering an operation outside the lifetime of your app are syncing data with a server. This was a case where you might was tempted to use a repeating alarm. But if you own the server so is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with Sync Ada Pter is a better solution than Alarmmanager. A Sync adapter gives the same scheduling options as Alarmmanager, but it offers you significantly more flexibility . For example, a sync could is based on a "new data" message from the Server/device (see Running a sync Adapter for details) The user's activity (or inactivity), the time of day, and so on. See the linked videos at the top of the "This" for a detailed discussion of "and" to use GCM and sync adapter.

Best practices

Every choice you do in designing your repeating alarm can has consequences in how your app uses (or abuses) system Reso Urces. For example, imagine a popular app, this syncs with a server. If The sync operation is based on clock time and every instance of the app syncs at 11:00AM, the load on the server cou LD result in high latency or even "denial of service." Follow these best practices in using alarms:

  • Add randomness (jitter) to any network requests that trigger as a result of a repeating alarm:
      • The alarm triggers. "Local work" means anything that doesn ' t hits a server or require the data from the server.
      • At the same time, schedule the alarm, which contains the network requests to fire at some random period of time.
  • Keep your alarm frequency to a minimum.
  • Don ' t wake up the device unnecessarily (this behavior was determined by the alarm type, as described in Choose an alarm Typ e).
  • Don ' t make your alarm's trigger time any more precise than it have to be. Use Setinexactrepeating () instead of setrepeating (). When you use Setinexactrepeating (), Android synchronizes repeating alarms from multiple apps and fires them at the same ti Me. This reduces the total number of times the system must wake the device, thus reducing drain on the battery. As of Android 4.4 (API level), all repeating alarms is inexact. Note that while setinexactrepeating () are an improvement over setrepeating (), it can still overwhelm a server if every inst Ance of an app hits the server around the same time. Therefore, for network requests, add some randomness to your alarms, as discussed above.
  • Avoid basing your alarm on clock time if possible. Repeating alarms that is based on a precise trigger time don ' t scale well. Use the Elapsed_realtime if you can. The different alarm types is described in more detail in the following section.

Set a repeating Alarm

As described above, repeating alarms is a good choice for scheduling regular events or data lookups. A repeating alarm has the following characteristics:

    • A alarm type. For more discussion, see Choose an alarm type.
    • A trigger time. If the trigger time you specify are in the past, the alarm triggers immediately.
    • The alarm ' s interval. For example, once a day, every hour, every 5 seconds, and so on.
    • A pending intent that fires then the alarm is triggered. When you set a second alarm that uses the same pending intent, it replaces the original alarm.

Choose an alarm type

One of the first considerations in using a repeating alarm is, what's its type should be.

There is both general clock types for alarms: "Elapsed real Time" and "Real Time Clock" (RTC). Elapsed Real Time uses the "time since system boot" as a reference, and real Time clock uses UTC (wall clock) time. This means, elapsed real time was suited to setting a alarm based on the passage of time (for example, a alarm that f Ires every seconds) since it isn ' t affected by time Zone/locale. The real time clock type is better suited for alarms that's dependent on current locale.

Both types has a "wakeup" version, which says to wake up the device's CPU if the screen is off. This ensures the alarm would fire at the scheduled time. This was useful if your app has a time dependency-for example, if it had a limited window to perform a particular operation . If you don't use the wakeup version of your alarm type and then all the repeating alarms would fire when your device is next a Wake.

If you simply need your alarm to fire at a particular interval (for example, every half hour), use one of the elapsed real Time types. In general, this is the better choice.

If you need your alarm to fire at a particular time of day, then choose one of the clock-based real time clock types. Note, however, that's this approach can has some Drawbacks-the app May is not translate well to other locales, and if the user Changes the device ' s time setting, it could cause unexpected behavior in your app. Using a real time clock alarm type als o does not scale well, as discussed above. We recommend that the "elapsed real time" alarm if you can.

Here is the list of types:

    • Elapsed_realtime-fires the pending intent based on the amount of time since the device is booted, but doesn ' t wake up the Device. The elapsed time includes any time during which the device is asleep.
    • Elapsed_realtime_wakeup-wakes up the device and fires the pending intent after the specified length of time have ELAPSED si NCE device BOOT.
    • Rtc-fires the pending intent at the specified time and does not wake up the device.
    • Rtc_wakeup-wakes up the device to fire the pending intent at the specified time.

Elapsed_realtime_wakeup examples

Here is some examples of using elapsed_realtime_wakeup.

Wake up the device to fire the alarm in minutes, and every-minutes after:

. (.,

Alarmmanagerinterval_half_hour Alarmmanager.interval_half_hour, alarmintent);

Wake up the device to fire a one-time (non-repeating) alarm in one minute:

Alarmmgr;

Alarmintent;

=(). (.);

Intent (, Alarmreceiverclass);

=pendingintentgetbroadcastcontext, 0);

. (.,

Systemclockelapsedrealtime *, alarmintent);

RTC examples

Here is some examples of using rtc_wakeup.

Wake up the device to fire the alarm at approximately, and repeat once a day at the same time:

Calendar. ();

. (. ());

. (., 14);

. (.,. (),

Alarmmanager.interval_day, alarmintent);

Wake up the device to fire the alarm at precisely-a.m., and every minutes thereafter:

Alarmmgr;

Alarmintent;

=(). (.);

Intent (, Alarmreceiverclass);

=pendingintentgetbroadcastcontext, 0);

Calendar. ();

. (. ());

. (., 8);

. (., 30);

. (.,. (),

Alarmintent);

Decide how precise your alarm needs to be

As described above, choosing the alarm type is often the first step in creating an alarm. A further distinction is what precise you need your alarm to be. For most apps, setinexactrepeating () are the right choice. When you use this method, Android synchronizes multiple inexact repeating alarms and fires them at the same time. This reduces the drain on the battery.

For the rare app this has rigid time requirements-for example, the alarm needs to fire precisely at 8:30am a.m., and every H Our on the Hour Thereafter-use setrepeating (). But you should avoid using exact alarms if possible.

With setinexactrepeating (), you can ' t specify a custom interval the the the-the-setrepeating (). You had to use one of the interval constants, such as Interval_fifteen_minutes, Interval_day, and so on. See Alarmmanager for the complete list.

Cancel an Alarm

Depending on your app, you may want to include the ability to cancel the alarm. To cancel a alarm, call Cancel () on the alarm Manager, passing in the pendingintent your no longer want to fire. For example:

Alarmmgr) {

. ();

}

Start an Alarm when the Device Boots

By default, all alarms is canceled when a device is shuts down. To prevent this from happening, can design your application to automatically restart a repeating alarm if the user Reb Oots the device. This ensures the Alarmmanager would continue doing its task without the user needing to manually restart the alarm.

Here is the steps:

  1. Set the receive_boot_completed permission in your application ' s manifest. This allows your app to receive the action_boot_completed, that's broadcast after the system finishes booting (this only W Orks If the app has already been launched by the user at least once): <uses-permission android:name= "android.permission . Receive_boot_completed "/>
  2. Implement a broadcastreceiver to receive the broadcast:
  3. Onreceivecontext,intent) {
  4. Intentgetactionequals "Android.intent.action.BOOT_COMPLETED"//Set the alarm here.
  5. }
  6. ADD the receiver to your app's manifest file with a intent filter that filters on the action_boot_completed ACTION: <r Eceiver android:name= ". Samplebootreceiver "
  7. =
  8. <intent-filter>
  9. =></action>
  10. </intent-filter>
  11. </receiver>
    Notice the manifest, the boot receiver is set to Android:enabled= "false". This means the receiver won't be called unless the application explicitly enables it. This prevents the boot receiver from being called unnecessarily. You can enable a receiver (for example, if the user sets a alarm) as follows:
    ComponentName receiver = new ComponentName (context, samplebootreceiver.class);
  12. Packagemanager=. ();
  13. Pmsetcomponentenabledsettingreceiver.,
  14. Packagemanager.dont_kill_app);
    Once you enable the receiver this, it would stay enabled, even if the user reboots the device. In other words, programmatically enabling the receiver overrides the manifest setting, even across reboots. The receiver would stay enabled until your app disables it. You can disable a receiver (for example, if the user cancels an alarm) as follows:
    ComponentName receiver = new ComponentName (context, samplebootreceiver.class);
  15. Packagemanager=. ();
  16. Pmsetcomponentenabledsettingreceiver.,
  17. .);

Android official article Translation Management device wake-up status (Managing Device Awake State)

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.