WorkManager از Workerهای طولانی مدت پشتیبانی داخلی دارد. در چنین مواردی، WorkManager میتواند به سیستم عامل سیگنالی ارسال کند که در صورت امکان، در حین اجرای این کار، فرآیند باید فعال نگه داشته شود. این Workerها میتوانند بیش از 10 دقیقه اجرا شوند. نمونههایی از موارد استفاده از این ویژگی جدید شامل آپلودها یا دانلودهای حجیم (که نمیتوان آنها را تکهتکه کرد)، پردازش یک مدل یادگیری ماشین به صورت محلی یا کاری است که برای کاربر برنامه مهم است.
در پشت صحنه، WorkManager یک سرویس پیشزمینه را از طرف شما مدیریت و اجرا میکند تا WorkRequest اجرا کند، ضمن اینکه یک اعلان قابل تنظیم نیز نمایش میدهد.
ListenableWorker اکنون از API مربوط به setForegroundAsync() پشتیبانی میکند و CoroutineWorker از API مربوط به setForeground() که در حال تعلیق است، پشتیبانی میکند. این APIها به توسعهدهندگان اجازه میدهند مشخص کنند که این WorkRequest ) مهم (از دیدگاه کاربر) یا طولانی مدت است.
از 2.3.0-alpha03 به بعد، WorkManager به شما امکان میدهد یک PendingIntent ایجاد کنید که میتواند برای لغو workerها بدون نیاز به ثبت یک کامپوننت اندروید جدید با استفاده از API createCancelPendingIntent() استفاده شود. این رویکرد به ویژه هنگام استفاده از APIهای setForegroundAsync() یا setForeground() مفید است که میتوانند برای افزودن یک اکشن اعلان برای لغو Worker استفاده شوند.
ایجاد و مدیریت کارگران با سابقه طولانی
بسته به اینکه با کاتلین یا جاوا کد مینویسید، از رویکردی کمی متفاوت استفاده خواهید کرد.
کاتلین
توسعهدهندگان کاتلین باید از 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 استفاده میکنند میتوانند 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 با مدت زمان طولانی اضافه کنید
اگر برنامه شما اندروید ۱۴ (سطح API ۳۴) یا بالاتر را هدف قرار میدهد، باید برای همه workerهای طولانی مدت ، نوع سرویس پیشزمینه را مشخص کنید. اگر برنامه شما اندروید ۱۰ (سطح API ۲۹) یا بالاتر را هدف قرار میدهد و شامل یک worker طولانی مدت است که نیاز به دسترسی به موقعیت مکانی دارد، مشخص کنید که worker از نوع سرویس پیشزمینه location استفاده میکند.
اگر برنامه شما اندروید ۱۱ (سطح API 30) یا بالاتر را هدف قرار میدهد و شامل یک worker طولانی مدت است که نیاز به دسترسی به دوربین یا میکروفون دارد، به ترتیب نوع سرویس پیشزمینه camera یا microphone را اعلام کنید.
برای افزودن این نوع سرویسهای پیشزمینه، مراحل شرح داده شده در بخشهای بعدی را تکمیل کنید.
انواع سرویسهای پیشزمینه را در مانیفست برنامه اعلام کنید
نوع سرویس پیشزمینهی worker را در مانیفست برنامهی خود اعلام کنید. در مثال زیر، worker نیاز به دسترسی به موقعیت مکانی و میکروفون دارد:
فایل 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); }