后台处理指南

发布时间 2023-12-04 15:32:10作者: papering

后台处理指南  |  Android 开发者  |  Android Developers https://developer.android.google.cn/guide/background?hl=zh-cn

Processing data in the background is an important part of creating an Android application that is both responsive for your users as well as a good citizen on the Android platform. Doing work on the main thread can lead to poor performance and therefore a poor user experience.

This guide explains what qualifies as background work, defines background task categories, provides you with criteria to categorize your tasks, and recommends APIs that you should use to execute them.

Core principle

In general, you should take any blocking tasks off the UI thread. Common long-running tasks include things like decoding a bitmap, accessing storage, working on a machine learning (ML) model, or performing network requests.

Definition of background work

An app is running in the background when both the following conditions are satisfied:

  • None of the app's activities are currently visible to the user.
  • The app isn't running any foreground services that started while an activity from the app was visible to the user.

Otherwise, the app is running in the foreground.

Note: Consider a case in which a foreground service starts while an activity from the app is visible to the user. The user subsequently navigates away from the app and returns to the home screen. In such cases, the app is running in the foreground until the service's lifecycle ends.

Common types of background work

Background work falls into one of three primary categories:

  • Immediate: Needs to execute right away and complete soon.
  • Long Running: May take some time to complete.
  • Deferrable: Does not need to run right away.

Likewise, background work in each of these three categories can be either persistent or impersistent:

  • Persistent work: Remains scheduled through app restarts and device reboots.
  • Impersistent work: No longer scheduled after the process ends.

 Figure 1: Types of background work.