WorkManager از کارگران با اجرای طولانی پشتیبانی داخلی دارد. در چنین مواردی، WorkManager میتواند سیگنالی به سیستمعامل ارائه دهد که درصورت امکان، فرایند باید درحین اجرای این کار فعال نگه داشته شود. این Workers میتواند بیشتر از ۱۰ دقیقه اجرا شود. نمونههای کاربرد این ویژگی جدید شامل بارگذاری یا بارگیری انبوه (که نمیتواند تکهتکه شود)، پردازش محلی مدل یادگیری ماشین، یا تکلیفی است که برای کاربر برنامه مهم است.
در پشت صحنه، WorkManager یک سرویس پیشزمینهای را ازطرف شما مدیریت و اجرا میکند
تا WorkRequest را اجرا کند، و درعینحال یک اعلان قابلپیکربندی را نیز نشان میدهد.
ListenableWorker اکنون از میانای برنامهسازی کاربردی setForegroundAsync() پشتیبانی میکند، و
CoroutineWorker از میانای برنامهسازی کاربردی تعلیق setForeground() پشتیبانی میکند. این
میاناهای برنامهسازی کاربردی به توسعهدهندگان اجازه میدهد مشخص کنند که این WorkRequest مهم (از
دیدگاه کاربر) یا طولانی است.
از 2.3.0-alpha03، WorkManager به شما امکان میدهد
PendingIntent ایجاد کنید که میتوان از آن برای لغو کردن کارگران بدون نیاز به
ثبت مؤلفه Android جدید بااستفاده از
میانای برنامهسازی کاربردی createCancelPendingIntent() استفاده کرد. این رویکرد بهویژه زمانی مفید است که با
میاناهای برنامهسازی کاربردی setForegroundAsync() یا setForeground() استفاده شود، که میتوان از آنها برای افزودن
کنش اعلان برای لغو Worker استفاده کرد.
ایجاد و مدیریت کارگران طولانیمدت
بسته به اینکه به زبان Kotlin یا Java کدنویسی میکنید، از رویکرد کمی متفاوتی استفاده خواهید کرد.
کاتلین
توسعهدهندگان Kotlin باید از CoroutineWorker استفاده کنند. بهجای استفاده از
setForegroundAsync()، میتوانید از نسخه تعلیق آن روش استفاده کنید،
setForeground().
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"
}
}
جاوا
توسعهدهندگانی که از ListenableWorker یا Worker استفاده میکنند میتوانند
setForegroundAsync() API را فراخوانی کنند که ListenableFuture<Void> را برمیگرداند. همچنین میتوانید برای بهروزرسانی Notification درحال انجام، با setForegroundAsync() تماس بگیرید.
در اینجا نمونه سادهای از یک کارگر طولانیمدت که فایلی را بارگیری میکند آورده شده است. این
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
}
}
افزودن نوع سرویس پیشزمینهای به کارگر طولانیمدت
اگر برنامهتان Android 14 (سطح میانای برنامهسازی کاربردی ۳۴) یا بالاتر را هدف قرار میدهد، باید برای همه پردازشهای طولانیمدت،
نوع سرویس پیشزمینهای مشخص کنید.
اگر برنامهتان Android 10 (سطح میانای برنامهسازی کاربردی ۲۹) یا بالاتر را هدف قرار میدهد و حاوی یک
کارگر طولانیمدت است که نیاز به دسترسی به مکان دارد، نشان دهید که کارگر
از نوع سرویس پیشزمینهای location استفاده میکند.
اگر برنامهتان Android 11 (سطح میانای برنامهسازی کاربردی ۳۰) یا بالاتر را هدف قرار میدهد
و حاوی کارگر طولانیمدتی است که به دسترسی به دوربین یا میکروفون نیاز دارد،
بهترتیب نوع سرویس پیشزمینه camera یا microphone را
اعلام کنید.
برای افزودن این انواع سرویس پیشزمینهای، مراحل شرحدادهشده در بخشهای زیر را تکمیل کنید.
اعلام کردن انواع سرویس پیشزمینهای در مانیفست برنامه
نوع سرویس پیشزمینهای کارگر را در مانیفست برنامهتان اعلام کنید. در مثال زیر، کارگر به دسترسی به مکان و میکروفون نیاز دارد:
AndroidManifest.xml
<service android:name="androidx.work.impl.foreground.SystemForegroundService" android:foregroundServiceType="location|microphone" tools:node="merge" />
مشخص کردن انواع سرویس پیشزمینهای در زمان اجرا
وقتی setForeground() یا setForegroundAsync() را فراخوانی میکنید، حتماً
نوع سرویس پیشزمینهای را مشخص کنید.
MyLocationAndMicrophoneWorker
کاتلین
private fun createForegroundInfo(progress: String): ForegroundInfo { // ... return ForegroundInfo(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_LOCATION or FOREGROUND_SERVICE_TYPE_MICROPHONE) }
جاوا
@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); }