1

In Android Oreo, I want to create a service that periodically updates data from the network.

class NetworkJobService : JobService() {
override fun onStopJob(p0: JobParameters?): Boolean {
    jobFinished(p0,true)
    return true
}

override fun onStartJob(p0: JobParameters?): Boolean {
    //Average working time 3 to 5 minutes
    NetworkConnect.connect()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doFinally {
                jobFinished(p0,true)
            }
            .subscribe({result->
                // Writes the parameters to the cache with the current time.
                Cache.write("result : $result")
            },{e->
                // Writes the parameters to the cache with the current time.
                Cache.write(e)
            })
     return true

    }
}

This service is registered in the schedule when you run MainActivity.

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    jobSchedule()
    button.setOnClickListener { readLog() }
}

val interval = 1000 * 60 * 15L

private fun jobSchedule(){
    val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
    val jobInfo = JobInfo.Builder(3,
            ComponentName(this, NetworkJobService::class.java))
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPeriodic(interval)
            .build()
    jobScheduler.schedule(jobInfo)
}

private fun readLog(){
    //The log file is read line by line.
    Cache.read()
            .reversed()
            .toObservable()
            .subscribe({ text->
                Log.i("Service Log",text)
            },{

            })
}
}

However, when I read the log file and checked the results, the service was running only when the MainActivity was running. In other words, it was not being rescheduled.

1) Run the activity and just turn off the device's screen

2) Run the activity and press the Home button to return to the launcher.

3) When the service is terminated and the app is deleted in the multitasking window

The most I wanted was to work in case 3), but in any of the above, the services I wanted were not rescheduled.

What have I missed?

H.Kim
  • 525
  • 4
  • 14

1 Answers1

-1

While working with background threads in Oreo when the app is in killed you need to start the services as foreground service. Here is the details of the same. Essentially, show a notification to make the user aware that your app is trying to doing something in the background. Hope it helps you.

ishan_307
  • 21
  • 3
  • The linked document says that you can mitigate background restrictions on Oreo via JobScheduler, and I'm running the service through JobScheduler, not startService. Do I need to find another way without using JobScheduler? – H.Kim Oct 18 '18 at 13:19