如果您需要执行可能需要很长时间的数据传输,可以创建 一个 JobScheduler 作业,并将其标识为用户发起的数据 传输 (UIDT) 作业。UIDT 作业适用于由设备用户发起的持续时间较长的数据传输,例如从远程服务器下载文件。UIDT 作业是在 Android 14(API 级别 34)中引入的。
由用户发起的数据传输作业由用户启动。这些作业需要一个通知,会立即启动,并且可能在系统条件允许的情况下长时间运行。您可以同时运行多个由用户发起的数据传输作业。
必须在应用对用户可见的情况下(或在某个允许的条件下)安排由用户发起的作业。满足所有限制条件后,操作系统可以执行由用户发起的作业,具体取决于系统运行状况限制。系统还可以根据提供的估算载荷大小来确定作业的执行时长。
排定使用者啟動的資料移轉作業
如需运行用户发起的数据传输作业,请执行以下操作:
确保您的应用已在其清单中声明
JobService和关联的 权限:<service android:name="com.example.app.CustomTransferService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="false"> ... </service>此外,还要为数据传输定义
JobService的具体子类:Kotlin
class CustomTransferService : JobService() { ... }
Java
class CustomTransferService extends JobService() { .... }
在清单中声明
RUN_USER_INITIATED_JOBS权限:<manifest ...> <uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" /> <application ...> ... </application> </manifest>构建
JobInfo对象时,调用setUserInitiated()方法。(此方法从 Android 14 开始提供。) 我们还建议您在创建作业时通过调用setEstimatedNetworkBytes()提供载荷大小 估算值 。Kotlin
val networkRequestBuilder = NetworkRequest.Builder() // Add or remove capabilities based on your requirements. // For example, this code specifies that the job won't run // unless there's a connection to the internet (not just a local // network), and the connection doesn't charge per-byte. .addCapability(NET_CAPABILITY_INTERNET) .addCapability(NET_CAPABILITY_NOT_METERED) .build() val jobInfo = JobInfo.Builder(jobId, ComponentName(mContext, CustomTransferService::class.java)) // ... .setUserInitiated(true) .setRequiredNetwork(networkRequestBuilder) // Provide your estimate of the network traffic here .setEstimatedNetworkBytes(1024 * 1024 * 1024, 1024 * 1024 * 1024) // ... .build()
Java
NetworkRequest networkRequest = new NetworkRequest.Builder() // Add or remove capabilities based on your requirements. // For example, this code specifies that the job won't run // unless there's a connection to the internet (not just a local // network), and the connection doesn't charge per-byte. .addCapability(NET_CAPABILITY_INTERNET) .addCapability(NET_CAPABILITY_NOT_METERED) .build(); JobInfo jobInfo = JobInfo.Builder(jobId, new ComponentName(mContext, CustomTransferService.class)) // ... .setUserInitiated(true) .setRequiredNetwork(networkRequest) // Provide your estimate of the network traffic here .setEstimatedNetworkBytes(1024 * 1024 * 1024, 1024 * 1024 * 1024) // ... .build();
执行作业时,对
JobService对象调用setNotification()。调用setNotification()会在任务管理器和状态栏通知区域中告知用户作业正在运行。执行完成后,调用
jobFinished()以向系统表明作业已完成,或者应重新调度作业。Kotlin
class CustomTransferService: JobService() { private val scope = CoroutineScope(Dispatchers.IO) @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) 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) // Execute the work associated with this job asynchronously. scope.launch { doDownload(params) } return true } private suspend fun doDownload(params: JobParameters) { // Run the relevant async download task, then call // jobFinished once the task is completed. jobFinished(params, false) } // Called when the system stops the job. override fun onStopJob(params: JobParameters?): Boolean { // Asynchronously record job-related data, such as the // stop reason. return true // or return false if job should end entirely } }
Java
class CustomTransferService extends JobService{ @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) @Override public boolean onStartJob(JobParameters params) { Notification notification = Notification.Builder(getBaseContext(), 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) // Execute the work associated with this job asynchronously. new Thread(() -> doDownload(params)).start(); return true; } private void doDownload(JobParameters params) { // Run the relevant async download task, then call // jobFinished once the task is completed. jobFinished(params, false); } // Called when the system stops the job. @Override public boolean onStopJob(JobParameters params) { // Asynchronously record job-related data, such as the // stop reason. return true; // or return false if job should end entirely } }
定期更新通知,让用户了解作业的状态和进度。如果在安排作业之前无法确定传输大小,或者需要更新估算的传输大小,请在知道传输大小之后使用新的 API
updateEstimatedNetworkBytes()更新传输大小。
建议
如需有效地运行 UIDT 作业,请执行以下操作:
明确定义网络限制和作业执行限制,以指定应何时执行作业。
在
onStartJob()中异步执行任务;例如,您可以使用 协程 来执行此操作。如果您不异步运行任务,则工作会在主线程上运行,并且可能会阻塞主线程,从而导致 ANR。为避免作业运行时间超出必要时长,请在传输完成时(无论成功还是失败)调用
jobFinished()。这样,作业就不会运行超出必要时长。如需了解作业停止的原因,请实现onStopJob()回调方法并调用JobParameters.getStopReason()。
回溯相容性
目前沒有支援 UIDT 作業的 Jetpack 程式庫。因此,建議您使用程式碼控管變更,確認您是在 Android 14 以上版本上執行作業。在較舊的 Android 版本中,您可以使用 WorkManager 的前景服務實作做為備用方法。
以下是檢查適當系統版本的程式碼範例:
Kotlin
fun beginTask() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { scheduleDownloadFGSWorker(context) } else { scheduleDownloadUIDTJob(context) } } private fun scheduleDownloadUIDTJob(context: Context) { // build jobInfo val jobScheduler: JobScheduler = context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler jobScheduler.schedule(jobInfo) } private fun scheduleDownloadFGSWorker(context: Context) { val myWorkRequest = OneTimeWorkRequest.from(DownloadWorker::class.java) WorkManager.getInstance(context).enqueue(myWorkRequest) }
Java
public void beginTask() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { scheduleDownloadFGSWorker(context); } else { scheduleDownloadUIDTJob(context); } } private void scheduleDownloadUIDTJob(Context context) { // build jobInfo JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(jobInfo); } private void scheduleDownloadFGSWorker(Context context) { OneTimeWorkRequest myWorkRequest = OneTimeWorkRequest.from(DownloadWorker.class); WorkManager.getInstance(context).enqueue(myWorkRequest) }
停止 UIDT 工作
使用者和系統均可停止由使用者啟動的移轉作業。
由工作管理員的使用者執行
The user can stop a user-initiated data transfer job that appears in the Task Manager.
At the moment that the user presses Stop, the system does the following:
- Terminates your app's process immediately, including all other jobs or foreground services running.
- Doesn't call
onStopJob()for any running jobs. - Prevents user-visible jobs from being rescheduled.
For these reasons, it's recommended to provide controls in the notification posted for the job to allow gracefully stopping and rescheduling the job.
Note that, under special circumstances, the Stop button doesn't appear next to the job in the Task Manager, or the job isn't shown in the Task Manager at all.
由系統執行
與一般工作不同的是,使用者啟動的資料移轉工作不會受到應用程式待命值區配額的影響。然而,若發生下列任一情況,系統也會停止工作:
- 某項限制不再符合開發人員定義的條件。
- 系統判定工作的執行時間比完成資料移轉工作所需的時間還要長。
- 系統會以系統健全狀態為優先考量,有鑑於溫度不斷升高,必須停止執行中的工作。
- 應用程式處理程序因裝置記憶體不足而終止。
如果系統因裝置記憶體不足以外的原因停止工作,系統會呼叫 onStopJob(),並在系統認定的最佳時間點重新執行工作。請確認即使系統未呼叫 onStopJob(),應用程式也可保持資料移轉狀態,並且確認再次呼叫 onStartJob() 後,應用程式可恢復此狀態。
可對使用者啟動的資料移轉作業進行排程的情況
應用程式必須在開放瀏覽權限的視窗中,或符合特定條件時,才能夠啟動使用者啟動的資料移轉作業:
- 如果應用程式可以從背景啟動活動,則也將可以從背景啟動使用者啟動的資料移轉作業。
- 如果應用程式只是在「近期活動」畫面的現有工作中,存在返回堆疊活動,則無法使系統允許執行使用者啟動的資料移轉作業。
如果排定在未滿足必要條件的時間執行作業,作業將會失敗,並傳回 RESULT_FAILURE 錯誤代碼。
使用者啟動的資料移轉作業許可的限制
为了支持在最佳时间点运行的作业,Android 提供了为每种作业类型分配约束条件的功能。这些约束条件从 Android 13 开始就已经可用。
注意:下表仅比较了因作业类型而异的约束条件。如需了解所有约束条件,请参阅 JobScheduler 开发者页面或工作约束条件。
下表显示了支持给定作业约束条件的不同作业类型,以及 WorkManager 支持的作业约束条件集。您可以使用表格前的搜索栏按作业约束方法的名称过滤表格。
以下是用户发起的数据传输作业允许使用的约束条件:
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
另請參閱
其他資源
如要進一步瞭解使用者發起的資料轉移作業,請參閱下列其他資源:
- 使用者啟動的資料轉移整合案例研究:Google 地圖使用使用者啟動的資料轉移 API,將下載可靠性提升 10%