ל-WorkManager יש תמיכה מובנית ב-workers לטווח ארוך. במקרים כאלה, WorkManager יכול לספק לאופרה אות לכך שצריך לשמור על התהליך פעיל, אם אפשר, בזמן ביצוע העבודה. משימות ה-Workers האלה יכולות לפעול במשך יותר מ-10 דקות. דוגמאות לתרחישים לדוגמה שבהם כדאי להשתמש בתכונה החדשה הזו כוללות העלאות או הורדות בכמות גדולה (שלא ניתן לפצל אותן), עיבוד נתונים מקומי של מודל למידת מכונה או משימה חשובה למשתמש של האפליקציה.
מתחת לפני השטח, WorkManager מנהל ומפעיל בשמכם שירות בחזית כדי להריץ את WorkRequest
, וגם מציג התראה שניתן להגדיר.
ListenableWorker
תומך עכשיו ב-API setForegroundAsync()
, ו-CoroutineWorker
תומך ב-API מושעה setForeground()
. ממשקי ה-API האלה מאפשרים למפתחים לציין ש-WorkRequest
הזה חשוב (מנקודת המבט של המשתמש) או לטווח ארוך.
החל מ-2.3.0-alpha03
, אפשר גם ליצור ב-WorkManager PendingIntent
, שאפשר להשתמש בו כדי לבטל משימות בלי לרשום רכיב Android חדש באמצעות ה-API createCancelPendingIntent()
. הגישה הזו שימושית במיוחד כשמשתמשים בממשקי ה-API setForegroundAsync()
או setForeground()
, שבהם אפשר להוסיף פעולת התראה לביטול ה-Worker
.
יצירה וניהול של משימות לטווח ארוך
תצטרכו להשתמש בגישה שונה במקצת בהתאם לשפת התכנות שבה אתם משתמשים – Kotlin או Java.
Kotlin
מפתחי 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"
}
}
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
}
}
הוספת סוג שירות שפועל בחזית לעובד לטווח ארוך
אם האפליקציה שלכם מטרגטת ל-Android 14 (רמת API 34) ואילך, עליכם לציין סוג של שירות שפועל בחזית לכל משימות העבודה הארוכות.
אם האפליקציה שלכם מטרגטת ל-Android 10 (רמת API 29) ואילך, ומכילה משימת עבודה ממושכת שדורשת גישה למיקום, עליכם לציין שהמשימת עבודה משתמשת בסוג שירות שפועל בחזית מסוג location
.
אם האפליקציה שלכם מטרגטת ל-Android 11 (רמת API 30) ואילך, ומכילה משימת עבודה ממושכת שדורשת גישה למצלמה או למיקרופון, עליכם להצהיר על סוגי השירותים בחזית camera
או microphone
, בהתאמה.
כדי להוסיף את סוגי השירותים האלה בחזית, צריך לבצע את השלבים שמפורטים בקטעים הבאים.
הצהרה על סוגי שירותים שפועלים בחזית במניפסט של האפליקציה
מגדירים את סוג השירות שפועל בחזית של העובד במניפסט של האפליקציה. בדוגמה הבאה, לעובד נדרשת גישה למיקום ולמיקרופון:
<service android:name="androidx.work.impl.foreground.SystemForegroundService" android:foregroundServiceType="location|microphone" tools:node="merge" />
ציון סוגי שירותים שפועלים בחזית בזמן הריצה
כשקוראים ל-setForeground()
או ל-setForegroundAsync()
, חשוב לציין סוג שירות שפועל בחזית.
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); }