تقديم الدعم للعاملين الدائمين

يتوافق WorkManager تلقائيًا مع الخدمات التي تعمل لفترة طويلة. في هذه الحالات، يمكن أن يرسل WorkManager إشارة إلى نظام التشغيل للإبقاء على العملية قيد التشغيل قدر الإمكان أثناء تنفيذ هذا العمل. يمكن أن تستمر هذه الخدمات لأكثر من 10 دقائق. تتضمّن حالات الاستخدام النموذجية لهذه الميزة الجديدة عمليات التحميل أو التنزيل المجمّعة (التي لا يمكن تقسيمها إلى أجزاء)، أو معالجة نموذج تعلُّم آلي محليًا، أو مهمة مهمة للمستخدم في التطبيق.

في الخلفية، يدير WorkManager خدمة تعمل في المقدّمة ويشغّلها نيابةً عنك لتنفيذ WorkRequest، مع عرض إشعار قابل للإعداد أيضًا.

ListenableWorker تتوافق الآن مع واجهة برمجة التطبيقات setForegroundAsync()، و CoroutineWorker تتوافق مع واجهة برمجة التطبيقات setForeground() التي يمكن تعليقها. تسمح واجهات برمجة التطبيقات هذه للمطوّرين بتحديد أنّ WorkRequest هذا مهم (من منظور المستخدم) أو يعمل لفترة طويلة.

بدءًا من 2.3.0-alpha03، يتيح لك WorkManager أيضًا إنشاء PendingIntent، الذي يمكن استخدامه لإلغاء الخدمات بدون الحاجة إلى تسجيل مكوّن Android جديد باستخدام createCancelPendingIntent() واجهة برمجة التطبيقات. يكون هذا النهج مفيدًا بشكل خاص عند استخدامه مع واجهات برمجة التطبيقات 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 استدعاء واجهة برمجة التطبيقات setForegroundAsync()، التي تعرض ListenableFuture<Void>. يمكنك أيضًا استدعاء setForegroundAsync() لتعديل Notification مستمر.

في ما يلي مثال بسيط على خدمة تعمل لفترة طويلة وتنزّل ملفًا. تتتبّع هذه الخدمة مستوى التقدّم لتعديل 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 (المستوى 34 لواجهة برمجة التطبيقات) أو الإصدارات الأحدث، عليك تحديد نوع خدمة تعمل في المقدّمة لجميع الخدمات التي تعمل لفترة طويلة. إذا كان تطبيقك يستهدف Android 10 (مستوى واجهة برمجة التطبيقات 29) أو الإصدارات الأحدث ويتضمّن خدمة تعمل لفترة طويلة وتتطلب الوصول إلى الموقع الجغرافي، عليك الإشارة إلى أنّ الخدمة تستخدم نوع خدمة تعمل في المقدّمة هو location.

إذا كان تطبيقك يستهدف Android 11 (المستوى 30 لواجهة برمجة التطبيقات) أو الإصدارات الأحدث ويتضمّن خدمة تعمل لفترة طويلة وتتطلب الوصول إلى الكاميرا أو الميكروفون، عليك تقديم بيان عن نوعَي خدمة تعمل في المقدّمة، وهما camera أو microphone على التوالي.

لإضافة أنواع الخدمات التي تعمل في المقدّمة هذه، يُرجى إكمال الخطوات الموضّحة في الأقسام التالية.

تقديم بيان عن أنواع الخدمات التي تعمل في المقدّمة في بيان التطبيق

عليك تقديم بيان عن نوع الخدمة التي تعمل في المقدّمة في بيان تطبيقك. في المثال التالي، تتطلب الخدمة الوصول إلى الموقع الجغرافي والميكروفون:

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);
}