Search code examples
androidscalakotlinservicescala-collections

How can we use the android JobIntentService in the Scala?


I can successfully extend and call the JobIntentService's function

enqueueWork(context, MessagesRetentionKotlin::class.java, UNIQUE_JOB_ID, work)

in the kotlin, but not in the Scala. Here I am sharing my Scala code for the class extending JobIntentService, will be great if someone can help me out. Thanks.

    class MessagesRetention(context: Context, work: Intent) extends  MessagesRetentionTrait with JobIntentService{
 
  override def onCreate():Unit= {
    super.onCreate()
    Log.d(TAG, "onCreate")
  }

 

  override def onHandleWork(intent: Intent):Unit=  {
    Log.d(TAG, "onHandleWork")
    val input: String = intent.getStringExtra("inputExtra")
    for (i <- 0 to 10) {
      Log.d(TAG, "$input - $i")
      if (isStopped) return
      SystemClock.sleep(1000)
    }
  }

  override def onDestroy():Unit=  {
    super.onDestroy()
    Log.d(TAG, "onDestroy")
    val serviceIntent =  new Intent(this, MessagesRetentionImpl.getClass)
    serviceIntent.putExtra("inputExtra", "Test")
    MessagesRetention.enqueueWorkk(this, serviceIntent)
  }
}

object MessagesRetention {
  private val TAG = "MessagesRetention"
  val UNIQUE_JOB_ID = 10101
  def  enqueueWorkk(context: Context, work: Intent):Unit=  {
     enqueueWork(context, MessagesRetentionImpl.getClass, UNIQUE_JOB_ID, work)
  }
}

Solution

  • Being a newbie in scala, I was not passing the right service context to the JobIntentService's enqueueWork method. Instead of using .getclass method I used the classOf[T] for service class passing and it worked.

    enqueueWork(context, classOf[MessagesRetention], UNIQUE_JOB_ID, work)