Android Workmanager: Wait for BroadcastReceiver before returning Result

Viewed 1113

I am sending SMS using SmsManager and I made use of WorkManager to be able to do it in background. Since the number of messages is dynamic, I chained WorkerRequest's for this. This is the snippet:

private fun startSmsWork(sms: Array<SmsEntity>) {
    val gson = Gson()

    val smsWorkerRequestBuilder = OneTimeWorkRequestBuilder<SmsWorker>()
      smsWorkerRequestBuilder.setInputData(workDataOf(SMS_WORKER_INPUT_KEY to gson.toJson(sms[0])))

    var continuation = WorkManager.getInstance()
      .beginWith(smsWorkerRequestBuilder.build())

    for (i in 1 until sms.size) {
      smsWorkerRequestBuilder.setInputData(workDataOf(SMS_WORKER_INPUT_KEY to gson.toJson(sms[i])))
      continuation = continuation.then(smsWorkerRequestBuilder.build())
    }

    continuation.enqueue()
}

And this is my worker class:

class SmsWorker(ctx: Context, workerParams: WorkerParameters) : Worker(ctx, workerParams) {

  override fun doWork(): Result {
    return try {
      val data = inputData.getString(SMS_WORKER_INPUT_KEY)
      val messages = Gson().fromJson(data, SmsEntity::class.java)
      sendSms(messages)
      Result.success()
    } catch (e: Exception) {
      Log.e("Sms", e.localizedMessage)
      Result.failure()
    }
  }

  private fun sendSms(msg: SmsEntity) {
    try {
      Log.d("SmsWorker", "Sending message ${msg.id}....")
      val sentIntent = Intent(SENT_INTENT_ACTION)
      sentIntent.putExtra(SENT_INTENT_EXTRA, msg.id)
      val sentPI = PendingIntent.getBroadcast(applicationContext, 0, sentIntent, 0)

      val deliveredIntent = Intent(DELIVERED_INTENT_ACTION)
      deliveredIntent.putExtra(DELIVERED_INTENT_EXTRA, msg.id)
      val deliveredPI = PendingIntent.getBroadcast(applicationContext, 0, sentIntent, 0)

      val smsManager = SmsManager.getDefault()
      smsManager.sendTextMessage(msg.num, null, msg.message, sentPI, deliveredPI)
    } catch (e: Exception) {
      Log.e("Sms", e.localizedMessage)
    }
  }
}

It works okay, BUT I want to be able to monitor each message sent. So I added a BroadcastReceiver for this but the intent that the BroadcastReceiver receives, would only be the latest one (in case of multiple messages). I found out that I have to wait for a message to be sent before sending one.

My question is how would I be able to implement this inside my worker class that it should wait for the result in BroadcastReceiver before returning the Result object.

Any input is much appreciated

1 Answers

If you want to wait asynchronously for the result of an operation during a worker, use a ListenableWorker.

Also, some general advice: since you're dealing with SMS, I'm pretty sure you will need a network constraint for your work. And you may also want to look at unique work and appending if that makes sense for your use case.

Related