Kotlin and Android rookie here...
I'm trying to create a job but I'm having some trobule gettint my async task to run. Here's my JobService:
class DbUpdaterJob: JobService(){
private var activityMessenger: Messenger? = null
private var isWorking = false
private var cancelled = false
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
//receive messenger used to get info back to the ui thread of activity
activityMessenger = intent?.getParcelableExtra(MESSENGER_DB_UPDATE_KEY)
return Service.START_NOT_STICKY
}
override fun onStartJob(params: JobParameters?): Boolean {
//asynctasks in order not to lock main thread
object: AsyncTask<Void, Void, Boolean>(){
override fun onPreExecute() {
super.onPreExecute()
}
override fun doInBackground(vararg params: Void?): Boolean {
isWorking = true
//do something
return true
}
override fun onPostExecute(result: Boolean?) {
isWorking = false
jobFinished(params, false)
//notify of update on main thread
if(result!!){
notifyActivity()
}
}
}.execute()
return true
}
override fun onStopJob(params: JobParameters?): Boolean {
cancelled = true
//if still working, must reschedule
jobFinished(params, isWorking)
return isWorking
}
private fun notifyActivity(){
val msg = Message.obtain()
msg.run {
what = MSG_DB_UPDATED
}
activityMessenger?.send(msg)
}
}
The idea is to put a couple of web services calls and local db code in the doInBackground. Unfortunately, it never gets called...Can someone please give some pointers on what I'm missing? I've also tried to rewrite the code with threads but still haven't got any luck with it. Not sure if it's important, but here's the code I'm using to schedule the job:
private fun scheduleJob(){
//NOTE: https://stackoverflow.com/questions/38344220/job-scheduler-not-running-on-android-n?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
//less than 15m does not work!
var jobInfo = JobInfo.Builder(DB_UPDATER_JOB_ID, serviceComponent)
.setRequiredNetworkType(NETWORK_TYPE_NOT_ROAMING)
.setPeriodic(4 * 60 * 60 *1000)
.build()
val scheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as? JobScheduler
val res = scheduler?.schedule(jobInfo)
Log.i("MainActivity", "Job scheduled with $res")
}