Nếu cần thực hiện một lệnh chuyển dữ liệu có thể mất nhiều thời gian, bạn có thể tạo một lệnh JobScheduler và xác định lệnh đó là lệnh chuyển dữ liệu do người dùng yêu cầu (UIDT). Các lệnh UIDT được thiết kế để chuyển dữ liệu trong thời gian dài do người dùng thiết bị yêu cầu, chẳng hạn như tải tệp xuống từ máy chủ từ xa. Các tác vụ UIDT được ra mắt cùng với Android 14 (API cấp 34).
Công việc chuyển dữ liệu do người dùng khởi tạo là công việc do người dùng đưa ra yêu cầu. Các công việc này đòi hỏi phải có thông báo, bắt đầu ngay lập tức và có thể chạy trong một khoảng thời gian dài nếu điều kiện của hệ thống cho phép. Bạn có thể chạy đồng thời một vài công việc chuyển dữ liệu do người dùng khởi tạo.
Các công việc do người dùng khởi tạo phải được lên lịch trong khi ứng dụng đang hiển thị cho người dùng (hoặc trong một trong các điều kiện được cho phép). Sau khi bạn đáp ứng tất cả các điều kiện ràng buộc, các hoạt động do người dùng yêu cầu có thể được hệ điều hành thực thi, tuân theo các hạn chế về tình trạng của hệ thống. Hệ thống cũng có thể sử dụng kích thước tải trọng (payload) ước tính được cung cấp để xác định thời gian thực hiện công việc này.
Lên lịch cho công việc chuyển dữ liệu do người dùng khởi tạo
如需运行用户发起的数据传输作业,请执行以下操作:
确保您的应用已在其清单中声明
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) // ... .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) // ... .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()
。
Khả năng tương thích ngược
There is currently no Jetpack library that supports UIDT jobs. For this reason, we recommend that you gate your change with code that verifies that you're running on Android 14 or higher. On lower Android versions, you can use WorkManager's foreground service implementation as a fallback approach.
Here's an example of code that checks for the appropriate system version:
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) }
Dừng các công việc UIDT
Both the user and the system can stop user-initiated transfer jobs.
Do người dùng đưa ra trên Trình quản lý tác vụ
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.
Do hệ thống
Khác với các công việc thông thường, công việc chuyển dữ liệu do người dùng khởi tạo sẽ không bị ảnh hưởng bởi hạn mức Bộ chứa chế độ chờ ứng dụng (App Standby Buckets). Tuy nhiên, hệ thống vẫn sẽ dừng công việc đó trong điều kiện bất kỳ sau đây:
- Không còn đáp ứng quy tắc ràng buộc do nhà phát triển xác định nữa.
- Hệ thống xác định rằng công việc đã chạy lâu hơn mức cần thiết để hoàn tất tác vụ chuyển dữ liệu.
- Tình trạng của hệ thống là vấn đề cần ưu tiên, đồng dừng công việc do nhiệt độ tăng.
- Dừng quá trình của ứng dụng do còn ít bộ nhớ trên thiết bị.
Khi hệ thống dừng công việc vì những lý do khác với việc thiết bị còn ít bộ nhớ, hệ thống sẽ gọi onStopJob()
và thử lại công việc đó vào thời điểm hệ thống cho là tối ưu. Đảm bảo rằng ứng dụng của bạn có thể duy trì trạng thái chuyển dữ liệu ngay cả khi onStopJob()
không được gọi, cũng như có thể khôi phục trạng thái này khi onStartJob()
được gọi lại.
Các điều kiện được cho phép để lên lịch công việc chuyển dữ liệu do người dùng khởi tạo
只有当应用处于可见窗口中或满足特定条件时,应用才能启动用户发起的数据传输作业:
- 如果应用可以从后台启动 activity,则也可以从后台启动用户发起的数据传输作业。
- 如果应用在最近用过屏幕上现有任务的返回堆栈中有 activity,单靠这一点并不允许运行用户发起的数据传输作业。
如果作业安排在未满足必要条件的时间运行,则作业将失败并返回 RESULT_FAILURE
错误代码。
Các hạn chế được cho phép đối với công việc chuyển dữ liệu do người dùng khởi tạo
To support jobs running at optimal points, Android offers the ability to assign constraints to each job type. These constraints are 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()
Thử nghiệm
The following list shows some steps on how to test your app's jobs manually:
- To get the job ID, get the value that is defined upon the job being built.
To run a job immediately, or to retry a stopped job, run the following command in a terminal window:
adb shell cmd jobscheduler run -f APP_PACKAGE_NAME JOB_ID
To simulate the system force-stopping a job (due to system health or out-of-quota conditions), run the following command in a terminal window:
adb shell cmd jobscheduler timeout TEST_APP_PACKAGE TEST_JOB_ID
Xem thêm
Tài nguyên khác
Để biết thêm thông tin về hoạt động chuyển dữ liệu do người dùng bắt đầu, hãy xem các tài nguyên bổ sung sau:
- Nghiên cứu điển hình về việc tích hợp UIDT: Google Maps cải thiện độ tin cậy khi tải xuống thêm 10% bằng cách sử dụng API chuyển dữ liệu do người dùng yêu cầu