WorkManager รองรับ Worker ที่ทำงานเป็นเวลานานในตัว ในกรณีดังกล่าว WorkManager จะส่งสัญญาณไปยังระบบปฏิบัติการว่าควรให้กระบวนการทำงานต่อไป หากเป็นไปได้ในขณะที่งานนี้กำลังดำเนินการอยู่ ซึ่งสามารถทำงานได้นานกว่า 10 นาที กรณีการใช้งานตัวอย่างสำหรับฟีเจอร์ใหม่นี้ ได้แก่ การอัปโหลดหรือดาวน์โหลดหลายรายการพร้อมกัน (ที่แบ่งเป็นหลายส่วนไม่ได้) การประมวลผลโมเดล ML ในเครื่อง หรือการทำงานที่สำคัญต่อผู้ใช้แอป
เบื้องหลัง WorkManager จะจัดการและเรียกใช้บริการที่ทำงานอยู่เบื้องหน้าในนามของคุณ
เพื่อดำเนินการ WorkRequest
พร้อมทั้งแสดงการแจ้งเตือนที่กำหนดค่าได้
ListenableWorker
รองรับ setForegroundAsync()
API แล้ว และ
CoroutineWorker
รองรับ API สำหรับการระงับ setForeground()
API เหล่านี้ช่วยให้นักพัฒนาแอประบุได้ว่า WorkRequest
นี้สำคัญ (จากมุมมองของผู้ใช้) หรือทำงานเป็นเวลานาน
ตั้งแต่ 2.3.0-alpha03
เป็นต้นไป WorkManager ยังช่วยให้คุณสร้าง PendingIntent
ได้ด้วย ซึ่งใช้ยกเลิก Worker ได้โดยไม่ต้องลงทะเบียนคอมโพเนนต์ Android ใหม่โดยใช้ createCancelPendingIntent()
API
แนวทางนี้มีประโยชน์อย่างยิ่งเมื่อใช้กับ API setForegroundAsync()
หรือ setForeground()
ซึ่งใช้เพื่อเพิ่มการดำเนินการแจ้งเตือนเพื่อยกเลิก Worker
ได้
การสร้างและจัดการ Worker ที่ทำงานเป็นเวลานาน
คุณจะต้องใช้วิธีการที่แตกต่างกันเล็กน้อย ขึ้นอยู่กับว่าคุณเขียนโค้ดใน Kotlin หรือ Java
Kotlin
นักพัฒนาซอฟต์แวร์ Kotlin ควรใช้ CoroutineWorker
คุณสามารถใช้เวอร์ชันระงับของวิธีการดังกล่าว
setForeground()
แทนการใช้
setForegroundAsync()
class DownloadWorker(context: Context, parameters: WorkerParameters) :
CoroutineWorker(context, parameters) {
private val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as
NotificationManager
override suspend fun doWork(): Result {
val inputUrl = inputData.getString(KEY_INPUT_URL)
?: return Result.failure()
val outputFile = inputData.getString(KEY_OUTPUT_FILE_NAME)
?: return Result.failure()
// Mark the Worker as important
val progress = "Starting Download"
setForeground(createForegroundInfo(progress))
download(inputUrl, outputFile)
return Result.success()
}
private fun download(inputUrl: String, outputFile: String) {
// Downloads a file and updates bytes read
// Calls setForeground() periodically when it needs to update
// the ongoing Notification
}
// Creates an instance of ForegroundInfo which can be used to update the
// ongoing notification.
private fun createForegroundInfo(progress: String): ForegroundInfo {
val id = applicationContext.getString(R.string.notification_channel_id)
val title = applicationContext.getString(R.string.notification_title)
val cancel = applicationContext.getString(R.string.cancel_download)
// This PendingIntent can be used to cancel the worker
val intent = WorkManager.getInstance(applicationContext)
.createCancelPendingIntent(getId())
// Create a Notification channel if necessary
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel()
}
val notification = NotificationCompat.Builder(applicationContext, id)
.setContentTitle(title)
.setTicker(title)
.setContentText(progress)
.setSmallIcon(R.drawable.ic_work_notification)
.setOngoing(true)
// Add the cancel action to the notification which can
// be used to cancel the worker
.addAction(android.R.drawable.ic_delete, cancel, intent)
.build()
return ForegroundInfo(notificationId, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
// Create a Notification channel
}
companion object {
const val KEY_INPUT_URL = "KEY_INPUT_URL"
const val KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME"
}
}
Java
นักพัฒนาแอปที่ใช้ ListenableWorker
หรือ Worker
สามารถเรียกใช้ API setForegroundAsync()
ซึ่งจะแสดงผล ListenableFuture<Void>
นอกจากนี้ คุณยังโทรหา setForegroundAsync()
เพื่ออัปเดต Notification
ที่กำลังดำเนินการอยู่ได้ด้วย
ต่อไปนี้เป็นตัวอย่างง่ายๆ ของ Worker ที่ทำงานเป็นเวลานานซึ่งดาวน์โหลดไฟล์ Worker นี้จะติดตามความคืบหน้าเพื่ออัปเดต Notification
ที่กำลังดำเนินการอยู่ ซึ่งจะแสดง
ความคืบหน้าในการดาวน์โหลด
public class DownloadWorker extends Worker {
private static final String KEY_INPUT_URL = "KEY_INPUT_URL";
private static final String KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME";
private NotificationManager notificationManager;
public DownloadWorker(
@NonNull Context context,
@NonNull WorkerParameters parameters) {
super(context, parameters);
notificationManager = (NotificationManager)
context.getSystemService(NOTIFICATION_SERVICE);
}
@NonNull
@Override
public Result doWork() {
Data inputData = getInputData();
String inputUrl = inputData.getString(KEY_INPUT_URL);
String outputFile = inputData.getString(KEY_OUTPUT_FILE_NAME);
// Mark the Worker as important
String progress = "Starting Download";
setForegroundAsync(createForegroundInfo(progress));
download(inputUrl, outputFile);
return Result.success();
}
private void download(String inputUrl, String outputFile) {
// Downloads a file and updates bytes read
// Calls setForegroundAsync(createForegroundInfo(myProgress))
// periodically when it needs to update the ongoing Notification.
}
@NonNull
private ForegroundInfo createForegroundInfo(@NonNull String progress) {
// Build a notification using bytesRead and contentLength
Context context = getApplicationContext();
String id = context.getString(R.string.notification_channel_id);
String title = context.getString(R.string.notification_title);
String cancel = context.getString(R.string.cancel_download);
// This PendingIntent can be used to cancel the worker
PendingIntent intent = WorkManager.getInstance(context)
.createCancelPendingIntent(getId());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
Notification notification = new NotificationCompat.Builder(context, id)
.setContentTitle(title)
.setTicker(title)
.setSmallIcon(R.drawable.ic_work_notification)
.setOngoing(true)
// Add the cancel action to the notification which can
// be used to cancel the worker
.addAction(android.R.drawable.ic_delete, cancel, intent)
.build();
return new ForegroundInfo(notificationId, notification);
}
@RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
// Create a Notification channel
}
}
เพิ่มประเภทบริการที่ทำงานอยู่เบื้องหน้าให้กับ Worker ที่ทำงานเป็นเวลานาน
หากแอปกำหนดเป้าหมายเป็น Android 14 (API ระดับ 34) ขึ้นไป คุณต้องระบุประเภทบริการที่ทำงานอยู่เบื้องหน้าสำหรับ Worker ที่ทำงานเป็นเวลานานทั้งหมด
หากแอปกำหนดเป้าหมายเป็น Android 10 (API ระดับ 29) ขึ้นไปและมี
Worker ที่ทำงานเป็นเวลานานซึ่งต้องเข้าถึงตำแหน่ง ให้ระบุว่า Worker
ใช้ประเภทบริการที่ทำงานอยู่เบื้องหน้าเป็น location
หากแอปกำหนดเป้าหมายเป็น Android 11 (API ระดับ 30) ขึ้นไป
และมี Worker ที่ทำงานเป็นเวลานานซึ่งต้องเข้าถึงกล้องหรือไมโครโฟน
ให้ประกาศประเภทบริการที่ทำงานอยู่เบื้องหน้า camera
หรือ microphone
ตามลำดับ
หากต้องการเพิ่มประเภทบริการที่ทำงานอยู่เบื้องหน้าเหล่านี้ ให้ทำตามขั้นตอนที่อธิบายไว้ในส่วนต่อไปนี้
ประกาศประเภทบริการที่ทำงานอยู่เบื้องหน้าในไฟล์ Manifest ของแอป
ประกาศประเภทบริการที่ทำงานอยู่เบื้องหน้าของ Worker ในไฟล์ Manifest ของแอป ในตัวอย่างต่อไปนี้ ผู้ปฏิบัติงานต้องมีสิทธิ์เข้าถึงตำแหน่งและไมโครโฟน
AndroidManifest.xml
<service android:name="androidx.work.impl.foreground.SystemForegroundService" android:foregroundServiceType="location|microphone" tools:node="merge" />
ระบุประเภทบริการที่ทำงานอยู่เบื้องหน้าที่รันไทม์
เมื่อเรียกใช้ setForeground()
หรือ setForegroundAsync()
ให้ตรวจสอบว่าคุณได้ระบุประเภทบริการที่ทำงานอยู่เบื้องหน้า
MyLocationAndMicrophoneWorker
Kotlin
private fun createForegroundInfo(progress: String): ForegroundInfo { // ... return ForegroundInfo(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_LOCATION or FOREGROUND_SERVICE_TYPE_MICROPHONE) }
Java
@NonNull private ForegroundInfo createForegroundInfo(@NonNull String progress) { // Build a notification... Notification notification = ...; return new ForegroundInfo(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_LOCATION | FOREGROUND_SERVICE_TYPE_MICROPHONE); }