Kotlin 和 Android 菜鸟在这里...
我正在尝试创建一份工作,但我的异步任务运行时遇到了一些麻烦。这是我的工作服务:
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)
}
}
这个想法是在 doInBackground 中放置几个 Web 服务调用和本地数据库代码。不幸的是,它永远不会被调用......有人可以指点一下我所缺少的东西吗?我也尝试用线程重写代码,但仍然没有任何运气。不确定它是否重要,但这是我用来安排工作的代码:
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")
}