preface

When our App is interacting with the user frequently, we need to handle a time-consuming task, and the result of the task needs immediate feedback. Since the main thread is used to process UI and user interaction logic, if too much time-consuming logic is executed in the main thread, it will block the main thread, causing ANR exceptions and causing APK to stall or even crash. Therefore, a background thread is required to handle time-consuming tasks.

When our App does not interact with users frequently, the App itself needs to periodically synchronize data or obtain data from the server (common heartbeat connection, long connection for sending and receiving messages). You need a background process to handle this, because background threads alone are not guaranteed to survive long enough to complete the task.

There are a lot of articles about process preservation, recommend a few good articles: Tencent — Zhang Xinghua original link can not find, this is others forward about Android process preservation, all you need to know

However, the official statement reads:

Note: You should only use a foreground service for tasks the user expects the system to execute immediately or without interruption. Such cases include uploading a photo to social media, or playing music even while the music-player app is not in the foreground. You should not start a foreground service simply to prevent the system from determining that your app is idle.

The purpose of this article is to refer to the official documentation to solve the problems related to background process processing.

Low power consumption (Doze) mode

Doze reduces battery consumption by delaying application background CPU and network activity.

The system periodically exits Doze for a period of time to allow the application to complete deferred activities. During this maintenance window, the system runs all pending synchronizations, jobs, and alerts and allows applications to access the network.

At the end of each maintenance window, the system enters Doze again, suspending network access and postponing jobs, syncing and alerting. Over time, the system schedules fewer and fewer maintenance Windows, helping to reduce battery consumption when the device is inactive for long periods of time when it is not connected to the charger.

Once the user wakes up the device by moving the device, opening the screen or connecting the charger, the system exits Doze and all applications resume normal activity.

Function limit

In low power mode, your application is limited by the following:

  • Pause network access.
  • The wakeup lock is ignored.
  • Standard AlarmManager alarm clock (includedsetExact()setWindow()) to the next maintenance period.
  • If you need to set the alarm to be triggered when the device is in low power mode, usesetAndAllowWhileIdle()setExactAndAllowWhileIdle(), but the alarm can only go off once in nine minutes. usesetAlarmClock()The set alarms will continue to trigger normally, and the system will exit low power mode shortly before these alarms trigger.
  • The system does not perform WLAN scan.
  • The system does not allow the synchronization adapter to run.
  • The system does not allow JobScheduler to run.

The ADB directive forces Doze mode

$adb shell dumpsys battery unplug $ADB shell dumpsys Deviceidle step Switching between the idle and active states $adb shell dumpsys deviceidle -h view help $adb shell dumpsys deviceidle force - idle [light | deep] Force to Idle $ADB shell dumpsys deviceidle force-inactive Force to inactive $ADB shell dumpsys deviceidle unforce Forcibly remove idle and Inactive states. Into the active state $adb shell dumpsys deviceidle get [light | deep | force | screen | charging | network] to get the current state of the corresponding $adb shell dumpsys Battery reset Resets the default value and restores the device activation status.Copy the code

Ii. Application Standby Mode (App Standby)

App Standby postpones background network activity for applications with which the user has not recently interacted.

The ADB command forces the standby mode

$adb shell dumpsys battery unplug $adb shell am set-inactive <packageName> true To enter standby mode $adb shell am Set-inactive <packageName> false Exits standby mode, $adb shell am get-inactive <packageName> Obtain the current status. $ADB shell Dumpsys battery reset Reset the default value.Copy the code

3. Optimization of different Versions of Android for power saving

In order to maximize battery power and enforce good application behavior, Android restricts background work when applications (or foreground service notifications) are not visible to the user.

Simulate the background running environment of App: adb shell cmd appops set RUN_IN_BACKGROUND ignore adb shell cmd appops set RUN_IN_BACKGROUND allow

The Android 6.0(API level 23)

Introduced Doze mode and App Standby management. Doze mode limits application behavior when the screen is off and the device is still. Application standby puts unused applications in a special state that limits their network access, job, and synchronization.

The Android 7.0(API level 24)

Limit implicit broadcasting and introduce Doze-on-the-Go (shorten the time to enter Doze mode and limit the timing priority).

Three implicit broadcasts are restricted: CONNECTIVITY_ACTION ACTION_NEW_PICTURE ACTION_NEW_VIDEO

The Android 8.0(API level 26)

Further limiting background behavior, such as obtaining location in the background and releasing cache wakeup locks.

Limit background processes: When the application is in the foreground, you can create foreground and background services at will. When the application just enters the background, it has a window for a few minutes. At this time, it can also create the foreground and background services at will. When the status is idle, the system terminates the background service of the application.

In most cases JobScheduler(official Demo) can replace background services and JobIntentService can replace IntentService.

Background applications can no longer start the service using startForegroundService(), only the startForegroundService() method. Then the application has 5 seconds to call the startForground() method to make the service foreground. If the method is not called within the specified time, The app will throw an ANR exception.

Implicit broadcast receivers cannot be registered (implicit broadcast is a broadcast that does not specify the target application, any application can receive such a broadcast). You can still register for explicit broadcasts. There are no more broadcasts that require signing permissions, because broadcasts will only be sent to apps with the same signature.

Android 9(API level 28)

App Standby Buckets are introduced, in which application requests for resources are dynamically prioritized according to application usage mode, consisting of five levels.

Active: frequently used or recently used apps Working Set: frequently used apps, but not every day Rare: rarely used apps Never: not used apps after installation

Fourth, the solution for power saving optimization

Best practices for ensuring that applications handle background tasks gracefully are as follows:

For deferred, asynchronous work that runs even if your device or application is restarted, use WorkManager. WorkManager can elegantly run delayable background work when operating conditions such as network availability and power are met.

  • WorkManager is backward compatible toAPI 14+.
    • API 23+Versions and above actually use JobScheduler
    • API 14-22Using theAlarmManager & BroadcastReceiver
  • You can add constraints for task execution, such as network status and charging status
  • It can handle one-off asynchronous tasks and periodic tasks
  • You can monitor and manage tasks that are already scheduled
  • Tasks are executed in sequence. Those triggered first are executed first
  • Ensures that the task is executed even if the application or device is restarted
  • It complies with the power saving characteristics and meets the power saving optimization requirements

Typical scenarios for using WorkManager:

  • Send logs, analytics to the backend server
  • Periodically fetch or synchronize data from the server

Add: reference

Official document WorkManagerSample