If you need to perform a data transfer that may take a long time, you can create a JobScheduler job and identify it as a user-initiated data transfer (UIDT) job. UIDT jobs are intended for longer-duration data transfers that are initiated by the device user, such as downloading a file from a remote server. UIDT jobs were introduced with Android 14 (API level 34).
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.
ตั้งเวลางานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้
หากต้องการเรียกใช้งานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้ ให้ทำดังนี้
ตรวจสอบว่าแอปได้ประกาศ
JobServiceและสิทธิ์ที่เกี่ยวข้อง ในไฟล์ Manifest แล้ว<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<manifest ...> <uses-permission android:name="android.permission.RUN_USER_INITIATED_JOBS" /> <application ...> ... </application> </manifest>เรียกใช้เมธอด
setUserInitiated()เมื่อสร้างออบเจ็กต์JobInfo(วิธีนี้ใช้ได้ตั้งแต่ 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();
ขณะที่งานกำลังดำเนินการ ให้เรียกใช้
setNotification()ในออบเจ็กต์JobServiceการเรียกใช้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()เช่น คุณสามารถทำได้โดยใช้โครูทีน หากไม่เรียกใช้ Task แบบไม่พร้อมกัน งานจะทำงานในเทรดหลักและอาจบล็อกเทรดหลัก ซึ่งอาจทำให้เกิด ANRหากต้องการหลีกเลี่ยงการเรียกใช้งานนานกว่าที่จำเป็น ให้เรียกใช้
jobFinished()เมื่อการโอนเสร็จสิ้น ไม่ว่าจะสำเร็จหรือล้มเหลว วิธีนี้จะช่วยให้งานไม่ทำงานนานเกินกว่าที่จำเป็น หากต้องการทราบสาเหตุที่งานหยุดทำงาน ให้ใช้เมธอดเรียกกลับonStopJob()และเรียกJobParameters.getStopReason()
ความเข้ากันได้แบบย้อนหลัง
ขณะนี้ยังไม่มีไลบรารี Jetpack ที่รองรับงาน UIDT ด้วยเหตุนี้ เราขอแนะนำให้คุณควบคุมการเปลี่ยนแปลงด้วยโค้ดที่ยืนยันว่าคุณ กำลังใช้ 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
ทั้งผู้ใช้และระบบสามารถหยุดงานการโอนที่ผู้ใช้เริ่มได้
โดยผู้ใช้จากตัวจัดการงาน
ผู้ใช้สามารถหยุดงานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้ซึ่งปรากฏในตัวจัดการงานได้
ขณะผู้ใช้กดหยุด ระบบจะทำดังนี้
- สิ้นสุดกระบวนการของแอปทันที รวมถึงงานหรือบริการอื่นๆ ทั้งหมดที่ทำงานอยู่เบื้องหน้า
- ไม่เรียกใช้
onStopJob()สำหรับงานที่ทำงานอยู่ - ป้องกันไม่ให้กำหนดเวลางานซึ่งผู้ใช้มองเห็นใหม่
ด้วยเหตุนี้ เราจึงขอแนะนำให้ระบุการควบคุมในการแจ้งเตือนที่โพสต์สำหรับงานเพื่อให้หยุดงานและกำหนดเวลาใหม่ได้อย่างราบรื่น
โปรดทราบว่าในบางกรณี ปุ่มหยุดจะไม่ปรากฏข้างงานใน Task Manager หรืองานจะไม่แสดงใน Task Manager เลย
โดยระบบ
งานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้จะไม่ได้รับผลกระทบจากโควต้า App Standby Buckets ซึ่งแตกต่างจากงานปกติ อย่างไรก็ตาม ระบบจะยังคงหยุดงานหากมีเงื่อนไขต่อไปนี้เกิดขึ้น
- ไม่เป็นไปตามข้อจำกัดที่นักพัฒนาแอปกำหนดอีกต่อไป
- ระบบพิจารณาว่างานทำงานนานเกินความจำเป็นในการ ดำเนินงานการโอนข้อมูลให้เสร็จสมบูรณ์
- ระบบต้องให้ความสำคัญกับสถานะของระบบและหยุดงานเนื่องจากสถานะความร้อนเพิ่มขึ้น
- ระบบจะปิดกระบวนการของแอปเนื่องจากหน่วยความจำของอุปกรณ์เหลือน้อย
เมื่อระบบหยุดงานเนื่องจากเหตุผลอื่นๆ นอกเหนือจากหน่วยความจำของอุปกรณ์เหลือน้อย ระบบจะเรียกใช้ onStopJob() และระบบจะลองทำงานอีกครั้งในเวลาที่ระบบเห็นว่าเหมาะสมที่สุด ตรวจสอบว่าแอปสามารถรักษาสถานะการโอนข้อมูลได้แม้ว่าจะไม่ได้เรียกใช้ onStopJob() และแอปสามารถกู้คืนสถานะนี้ได้เมื่อมีการเรียกใช้ onStartJob() อีกครั้ง
เงื่อนไขที่อนุญาตสำหรับการตั้งเวลางานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้
Apps can only start a user-initiated data transfer job if the app is in the visible window, or if certain conditions are met:
- If an app can launch activities from the background, it 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 to run at a time when the necessary conditions are not
met, the job fails and returns a RESULT_FAILURE error code.
ข้อจํากัดที่อนุญาตสําหรับงานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้
Android มีความสามารถในการกำหนดข้อจำกัดให้กับงานแต่ละประเภทเพื่อรองรับงานที่ทำงานในจุดที่เหมาะสมที่สุด ข้อจำกัดเหล่านี้พร้อมใช้งานตั้งแต่ Android 13 เป็นต้นไป
หมายเหตุ: ตารางต่อไปนี้จะเปรียบเทียบเฉพาะข้อจํากัดที่แตกต่างกันระหว่าง งานแต่ละประเภท ดูข้อจำกัดทั้งหมดได้ที่หน้าสำหรับนักพัฒนาซอฟต์แวร์ของ JobScheduler หรือข้อจำกัดของงาน
ตารางต่อไปนี้แสดงประเภทงานต่างๆ ที่รองรับข้อจำกัดของงานที่กำหนด รวมถึงชุดข้อจำกัดของงานที่ WorkManager รองรับ ใช้แถบค้นหาก่อนตารางเพื่อกรองตารางตามชื่อของเมธอดข้อจำกัดของงาน
ข้อจำกัดที่อนุญาตสำหรับงานการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้มีดังนี้
setBackoffCriteria(JobInfo.BACKOFF_POLICY_EXPONENTIAL)setClipData()setEstimatedNetworkBytes()setMinimumNetworkChunkBytes()setPersisted()setNamespace()setRequiredNetwork()setRequiredNetworkType()setRequiresBatteryNotLow()setRequiresCharging()setRequiresStorageNotLow()
การทดสอบ
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
ดูเพิ่มเติม
แหล่งข้อมูลเพิ่มเติม
ดูข้อมูลเพิ่มเติมเกี่ยวกับการโอนข้อมูลที่เริ่มต้นโดยผู้ใช้ได้จากแหล่งข้อมูลเพิ่มเติมต่อไปนี้
- กรณีศึกษาเกี่ยวกับการผสานรวม UIDT: Google Maps ปรับปรุงความน่าเชื่อถือในการดาวน์โหลดได้ 10% โดยใช้ User Initiated Data Transfer API