将前台服务迁移到用户发起的数据传输作业

Android 14 applies strict rules on when apps are allowed to use foreground services.

Also in Android 14 we are introducing a new API to specify that a job must be a user-initiated data transfer job. This API is helpful for use cases that require longer-duration, user-initiated transferring of data, such as downloading a file from a remote server. These types of tasks should use a user-initiated data transfer job.

User-initiated data transfer jobs are started by the user. These jobs require a notification, start immediately, and may be able to run for an extended period of time as system conditions allow. You can run several user-initiated data transfer jobs concurrently.

User initiated jobs must be scheduled while the application is visible to the user (or in one of the allowed conditions). After all constraints are met, user initiated jobs can be executed by the OS, subject to system health restrictions. The system may also use the provided estimated payload size to determine how long the job executes.

用户发起的数据传输作业的权限

由用户发起的数据传输作业需要具备以下新权限才能运行:RUN_USER_INITIATED_JOBS。系统会自动授予此权限。如果您未在应用清单中声明此权限,系统会抛出 SecurityException

安排用户发起的数据传输作业的流程

如需运行用户发起的作业,请执行以下操作:

  1. 如果这是您第一次使用 JobScheduler 声明 API,请在清单中声明 JobService 和相关权限。此外,还要为数据传输定义具体的 JobService 子类:

    <service android:name="com.example.app.CustomTransferService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="false">
            ...
    </service>
    
    class CustomTransferService : JobService() {
      ...
    }
    
  2. 在清单中声明 RUN_USER_INITIATED_JOBS 权限:

    <manifest ...>
        <uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" />
        <application ...>
            ...
        </application>
    </manifest>
    
  3. 在构建 JobInfo 对象时调用新的 setUserInitiated() 方法。我们还建议您在创建作业时通过调用 setEstimatedNetworkBytes() 提供载荷大小估算值:

    val networkRequestBuilder = NetworkRequest.Builder()
            .addCapability(NET_CAPABILITY_INTERNET)
            .addCapability(NET_CAPABILITY_NOT_METERED)
            // Add or remove capabilities based on your requirements
            .build()
    
    val jobInfo = JobInfo.Builder()
            // ...
            .setUserInitiated(true)
            .setRequiredNetwork(networkRequestBuilder.build())
            .setEstimatedNetworkBytes(1024 * 1024 * 1024)
            // ...
            .build()
    
  4. 在应用可见或在允许的条件列表中时,在转移开始之前调度作业:

    val jobScheduler: JobScheduler =
        context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
    jobScheduler.schedule(jobInfo)
    
  5. 执行作业时,请确保对 JobService 对象调用 setNotification()。该值用于在任务管理器和状态栏通知区域中告知用户作业正在运行:

    class CustomTransferService : JobService() {
      override fun onStartJob(params: JobParameters?): Boolean {
          val notification = Notification.Builder(applicationContext, NOTIFICATION_CHANNEL_ID)
                  .setContentTitle("My user-initiated data transfer job")
                  .setSmallIcon(android.R.mipmap.myicon)
                  .setContentText("Job is running")
                  .build()
    
          setNotification(params, notification.id, notification,
                  JobService.JOB_END_NOTIFICATION_POLICY_DETACH)
          // Do the job execution.
      }
    }
    
  6. 定期更新通知,让用户了解作业的状态和进度。如果在安排作业之前无法确定传输大小,或者需要更新估算的传输大小,请在知道传输大小后使用新的 API updateEstimatedNetworkBytes() 更新传输大小。

  7. 执行完成后,调用 jobFinished() 以向系统表明作业已完成,或者应重新调度作业。

可以停止用户发起的数据传输作业

用户和系统都可以停止用户发起的传输作业。

由用户从任务管理器提供

用户可以停止显示在任务管理器中的用户发起的传输作业。

在用户按 Stop 时,系统会执行以下操作:

  • 立即终止应用的进程,包括正在运行的所有其他作业或前台服务。
  • 不针对任何正在运行的作业调用 onStopJob()
  • 阻止重新调度用户可见的作业。

因此,建议在发布的作业通知中提供控件,以便顺利停止和重新调度作业。

请注意,在特殊情况下,Stop 按钮不会显示在任务管理器中的作业旁边,或者该作业根本不会显示在任务管理器中。

由系统提供

与常规作业不同,用户发起的数据传输作业不受应用待机模式存储分区配额的影响。但是,如果出现以下任一情况,系统仍会停止作业:

  • 不再满足开发者定义的约束条件。
  • 系统确定该作业的运行时间超出了完成数据传输任务所需的时间。
  • 系统需要优先考虑系统运行状况,并因发热程度上升而停止作业。
  • 应用进程因设备内存不足而被终止。

系统停止作业(并非因为内存不足)时,系统会调用 onStopJob(),系统会在系统认为最佳的时间重试作业。检查您的应用是否可以保留数据传输状态(即使未调用 onStopJob()),并且您的应用可以在再次调用 onStartJob() 时恢复此状态。

允许安排用户发起的数据传输作业的条件

Apps can only start a user-initiated data transfer job if the app is in the visible window, or if the certain conditions are met. To determine when a user-initiated data transfer job can be scheduled, the system applies the same list of conditions that allow apps to start an activity from the background in special cases. Notably, this list of conditions are not the same as the set of exemptions for background-started foreground service restrictions.

The exceptions to the previous statement are the following:

  • If an app can launch activities from the background, they can also launch user-initiated data transfer jobs from the background.
  • If an app has an activity in the back stack of an existing task on the Recents screen, that alone doesn't allow a user-initiated data transfer job to run.

If the job is scheduled at some other time not listed in the allowed conditions list, the job fails and returns a RESULT_FAILURE error code.

适用于用户发起的数据传输作业的约束条件

To support jobs running at optimal points, Android offers the ability to assign constraints to each job type. These constraints are already available as of Android 13.

Note: The following table only compares the constraints that vary between each job type. See JobScheduler developer page or work constraints for all constraints.

The following table shows the different job types that support a given job constraint, as well as the set of job constraints that WorkManager supports. Use the search bar before the table to filter the table by the name of a job constraint method.

These are the constraints allowed with user-initiated data transfer jobs:

  • setBackoffCriteria(JobInfo.BACKOFF_POLICY_EXPONENTIAL)
  • setClipData()
  • setEstimatedNetworkBytes()
  • setMinimumNetworkChunkBytes()
  • setPersisted()
  • setNamespace()
  • setRequiredNetwork()
  • setRequiredNetworkType()
  • setRequiresBatteryNotLow()
  • setRequiresCharging()
  • setRequiresStorageNotLow()

测试

下面列出了有关如何手动测试应用作业的一些步骤:

  • 如需获取作业 ID,请获取在构建作业时定义的值。
  • 如需立即运行作业或重试已停止的作业,请在终端窗口中运行以下命令:

    adb shell cmd jobscheduler run -f APP_PACKAGE_NAME JOB_ID
    
  • 如需模拟系统强行停止作业(由于系统运行状况或超出配额条件),请在终端窗口中运行以下命令:

    adb shell cmd jobscheduler timeout TEST_APP_PACKAGE TEST_JOB_ID