Uzun süreli çalışanlar için destek

WorkManager, uzun süre çalışan çalışanlar için yerleşik destek sunar. Bu gibi durumlarda WorkManager, OS'ye bu çalışma yürütülürken mümkünse işlemin etkin tutulması gerektiğini belirten bir sinyal gönderebilir. Bu işleyiciler 10 dakikadan uzun süre çalışabilir. Bu yeni özelliğin örnek kullanım alanları arasında toplu yükleme veya indirme (bölümlere ayrılamayan), yerel bir makine öğrenimi modelinde işleme veya uygulamanın kullanıcı için önemli bir görev yer alır.

WorkManager, WorkRequest'i yürütmek için sizin adınıza bir ön plan hizmetini yönetip çalıştırırken, yapılandırılabilir bir bildirim de gösterir.

ListenableWorker artık setForegroundAsync() API'yi, CoroutineWorker ise askıya alınmış setForeground() API'yi destekliyor. Bu API'ler, geliştiricilerin bu WorkRequest'nin önemli (kullanıcı açısından) veya uzun süreli olduğunu belirtmesine olanak tanır.

2.3.0-alpha03 sürümünden itibaren WorkManager, createCancelPendingIntent() API'sini kullanarak yeni bir Android bileşeni kaydetmenize gerek kalmadan işleyicileri iptal etmek için kullanılabilecek bir PendingIntent oluşturmanıza da olanak tanır. Bu yaklaşım, özellikle setForegroundAsync() veya setForeground() API'leriyle birlikte kullanıldığında yararlıdır. Bu API'ler, Worker'yi iptal etmek için bildirim işlemi eklemek amacıyla kullanılabilir.

Uzun süre çalışan çalışanlar oluşturma ve yönetme

Kotlin mi yoksa Java mı kullandığınıza bağlı olarak biraz farklı bir yaklaşım kullanacaksınız.

Kotlin

Kotlin geliştiricileri CoroutineWorker kullanmalıdır. setForegroundAsync() yerine bu yöntemin askıya alma sürümünü (setForeground()) kullanabilirsiniz.

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 veya Worker kullanan geliştiriciler, ListenableFuture<Void> döndüren setForegroundAsync() API'yi çağırabilir. Devam eden bir Notification'yi güncellemek için setForegroundAsync()'ü de arayabilirsiniz.

Aşağıda, dosya indiren uzun süre çalışan bir işleyicinin basit bir örneği verilmiştir. Bu İşçi, indirme ilerleme durumunu gösteren devam eden bir Notification öğesini güncellemek için ilerleme durumunu izler.

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

Uzun süre çalışan bir çalışana ön plan hizmet türü ekleme

Uygulamanız Android 14 (API düzeyi 34) veya sonraki sürümleri hedefliyorsa tüm uzun süre çalışan işleyiciler için bir ön plan hizmeti türü belirtmeniz gerekir. Uygulamanız Android 10 (API düzeyi 29) veya sonraki sürümleri hedefliyorsa ve konuma erişim gerektiren uzun süre çalışan bir işleyici içeriyorsa işleyicinin location ön plan hizmeti türünü kullandığını belirtin.

Uygulamanız Android 11'i (API düzeyi 30) veya sonraki sürümleri hedefliyorsa ve kameraya ya da mikrofona erişim gerektiren uzun süre çalışan bir işleyici içeriyorsa sırasıyla camera veya microphone ön plan hizmet türlerini belirtin.

Bu ön plan hizmet türlerini eklemek için aşağıdaki bölümlerde açıklanan adımları tamamlayın.

Ön plan hizmet türlerini uygulama manifest dosyasında beyan etme

İşleyicinin ön plan hizmet türünü uygulamanızın manifest dosyasında tanımlayın. Aşağıdaki örnekte, çalışanın konuma ve mikrofona erişmesi gerekiyor:

AndroidManifest.xml

<service
   android:name="androidx.work.impl.foreground.SystemForegroundService"
   android:foregroundServiceType="location|microphone"
   tools:node="merge" />

Çalışma zamanında ön plan hizmet türlerini belirtme

setForeground() veya setForegroundAsync() işlevini çağırırken ön plan hizmet türü belirtmeyi unutmayın.

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