Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet116/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   112   113   114   115   116   117   118   119   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

131
CHAPTER 8: APIs
jobThread = null
return true
}
}
The most important part of the implementation is the onStartJob() method. There you’ll 
enter the work the job is actually supposed to do. Note that we pushed the actual work into 
a thread. This is important because the onStartJob() method runs in the app’s main thread, 
thus blocking potentially important other work if it stays too long inside. Starting a thread 
instead finishes immediately. Also, we return true, signaling that the job continues doing its 
work in a background thread. Once the job finishes, it must call jobFinished(); otherwise, 
the system wouldn’t know that the job finished doing its work.
The overridden onStopJob() method is not part of the normal job lifecycle. It instead gets 
called when the system decides to finish the job prematurely. We let it return true to tell the 
system that it is allowed to reschedule the job, in case it was configured accordingly.
To finish the job implementation, we must still configure the service class inside 
AndroidManifest.xml. To do so, add the following:
android:label="MyJob Service"
android:permission=
"android.permission.BIND_JOB_SERVICE" />
The permission configured here is not a ”dangerous” permission, so you don’t have to 
implement a process to acquire this permission. However, you must add this permission 
here; otherwise, the job gets ignored.
To actually schedule a job governed by the JobScheduler, you first need to obtain a 
JobScheduler object as a system service. Then you can build a JobInfo object, and in the 
end you register it with the JobScheduler.
val jsched = getSystemService(JobScheduler::class.java)
val JOB_ID : Int = 7766
val service = ComponentName(this, MyJob::class.java)
val builder = JobInfo.Builder(JOB_ID, service)
.setMinimumLatency((1 * 1000).toLong())
// wait at least 1 sec
.setOverrideDeadline((3 * 1000).toLong())
// maximum delay 3 secs
jsched.schedule(builder.build())
This example schedules the job to be started, the earliest after one second and the latest 
after three seconds. By construction it gets the ID 7766 assigned. This is a value passed to 
onStartJob() inside the job implementation. The number is just an example; you can use 
any unique number for the ID.
While building the JobInfo object, you can set various job characteristics, as shown in
Table 
8-2
.



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   112   113   114   115   116   117   118   119   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling