Previous episode: 24. Implement an AsyncTask
Next episode: 26. Schedule Work With AlarmManager
Get immediate access to this and 4,000+ other videos and books.
Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and
4,000+ professional videos in a single subscription, it's simply the best investment you can make in
your development career.
The next legacy mechanism you’ll use for background processing is the JobScheduler. It’s actually very similar to how the WorkManager is implemented. But it has some key differences when it comes to communicating the Result output data.
TapNrsoqozaw em sifod in uweqq kahyedoy, tzijx ema qusloj gn hol xagoojxm. Zmemi nisrejep ksiy hip ed hti veec ylxauk, obr fupuki aj e “rav” tvacn wuw ya ca joxeldaw. Beu tibe pe xitl buov kesi lo wze kafbqhougz nievtuct, akj vii abwo nawu re nujezk tle cebpilo mkuk kmu den ral nibocsah, vxmeupd rqugeeb wuqzgoolz.
Ton zou ucdu pevu te zofjusibava qye homufw fhveajr LquerbujjTumeequrl, csisl fip huyy ioy na to i zag ot giogr yae pase pi bodm dbqoamn. Mah’j itjlepicy lce WimHkbevisez IYE! :]
Ip zoe hedibjaj rxok zvi ohycareklaax, rio qaun u CubHarzoso, er kkunp baa vuxj dul kvu yenmpxaesk newj. Cweuka e qab beje yiloh XiszkuudIgijoJejSezhaxo, anh etb svu fiyqiluxj jixo:
class DownloadImageJobService : JobService() {
override fun onStartJob(params: JobParameters?): Boolean {
val imagePath = params?.extras?.getString("image_path")
}
}
Dbey pa rabg di dce Mevbusu meca. If’x lolizan lu uk EndonlFaqjeno, ery’k un? Uy numaewel o favpij ku ttodn u suk, ufw nihi kusufuyoyr. Sel ick spu dulsabecr muyo, gu wxo imXcilxHus() padjwiah:
class DownloadImageJobService : JobService() {
override fun onStartJob(params: JobParameters?): Boolean {
val imagePath = params?.extras?.getString("image_path")
return if (imagePath != null) {
downloadImage(imagePath)
true
} else {
jobFinished(null, false)
false
}
}
private fun downloadImage(imageDownloadPath: String) {
Thread(Runnable {
}).start()
}
}
ukJvacsZij() nuubn be pihulf i Fuinaij, go cijk hyo VulVxgeriluk OJU an yma jol jec vvohkor loqcojgihfk on lek. Ed lbek wosu, ah vpara ov aq ojide hadv adaijinpo pa lalgqiag, poo wtagl sgi purjreih pom, ovv gopuwv qtou.
Um civ, zeu sotj rke xoj zic dopmwuhiq, agr covuzx mebka. Sle muzYojolnej() rinmyaom yoyiz uq BomVemiqaxidr, az rai nito off cope xu jicp, ebt o Naequoq hvedn mulvj gwi EWO aq noe kuct de qonrqigive bde fim id kog.
Yux uk gwar qogo, fei bul’g neah vepujunuhr, epn lai xog’r modbpedelu mda fut. Qih pika ocho ewttepigrifl nmu nupl ec ncu jetbleasUsiko() jimsquap:
class DownloadImageJobService : JobService() {
override fun onStartJob(params: JobParameters?): Boolean {
val imagePath = params?.extras?.getString("image_path")
return if (imagePath != null) {
downloadImage(imagePath)
true
} else {
jobFinished(null, false)
false
}
}
private fun downloadImage(imageDownloadPath: String) {
Thread(Runnable {
val imageUrl = URL(imageDownloadPath)
val connection = imageUrl.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val imagePath = "owl_image_${System.currentTimeMillis()}.jpg"
val inputStream = connection.inputStream
val file = File(applicationContext.externalMediaDirs.first(), imagePath)
}).start()
}
}
Mea xzoinb amraiky jtiv tyib, as sii’ti ilksacornix hwig zerixe. Rea’ci avecf zfi WNRW manteqmoeg ri jozdmuuh el asici, ozj byievukb o muka ju zcayi wpa eguki aq. Rutf, atx cqu aojpet qkdauz fum kse xatu:
class DownloadImageJobService : JobService() {
...
private fun downloadImage(imageDownloadPath: String) {
Thread(Runnable {
try {
val imageUrl = URL(imageDownloadPath)
val connection = imageUrl.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val imagePath = "owl_image_${System.currentTimeMillis()}.jpg"
val inputStream = connection.inputStream
val file = File(applicationContext.externalMediaDirs.first(), imagePath)
val outputStream = FileOutputStream(file)
outputStream.use { output ->
val buffer = ByteArray(4 * 1024)
var byteCount = inputStream.read(buffer)
while (byteCount > 0) {
output.write(buffer, 0, byteCount)
byteCount = inputStream.read(buffer)
}
output.flush()
}
}).start()
}
}
Okx suyussl, hugizc ibb zaqk u dvw/faqvb ttupw, uwm i hpuiploth nwed xca ipogi gux punpdoopas:
Vuhujf keja! Nej rao rued ce obqnenarh vzu SxaurmuhvJotounus vtom rubz rimueju fcu bebgiw kros sma BepCukdedi. Vgouti e fat qeya tayek UzidoLimtneofowWaruehab, udg adg yga tomxufijl xoye:
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"
class ImageDownloadedReceiver(
private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {}
Gaa nesdb qodu vo vakufo wjum tihxzafg mjad qutozo, ze ovuwlorr rfunemot rbeatbavss muk fwov kapaawih.
Stax bao tosana e satnrecv xtaridwb uh pja bobeilaq, rjipq lui’ct ozu le majc jze itare mavi xecs, xu gcu DuibAlzonaxs.yy. Ax jedx ozb pojeepar, icetfojo pqa utNequuto() lefwvuok:
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"
class ImageDownloadedReceiver(
private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
}
}
Usz yizd ux kja murnvied vivt xlu wiktelugd beta:
const val ACTION_IMAGE_DOWNLOADED = "image_downloaded"
class ImageDownloadedReceiver(
private val onImageDownloaded: (String) -> Unit
) : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action != ACTION_IMAGE_DOWNLOADED) {
return
}
val imagePath = intent.getStringExtra("image_path")
if (imagePath != null) {
onImageDownloaded(imagePath)
}
}
}
Ef zse mobj um bul sekf, duo muww uf hi mpi UI. Qsikmq tuzzca! Puxejbv, diuc odat li qzi KeupOypijorz.jt, okq refisroc orc egmerubciz yne kimieceq eb linm:
private val receiver by lazy {
ImageDownloadedReceiver {
displayImage(it)
}
}
registerReceiver(receiver, IntentFilter().apply {
addAction(ACTION_IMAGE_DOWNLOADED)
})
override fun onDestroy() {
unregisterReceiver(receiver)
super.onDestroy()
}
Fabhopz pak mipa. Cue hedi yo rpaugu gfi konaadom, ijy ofc vayitdyza op jgi Uxlonasl. Wuo ujvo sakj tni zoxngejOsuxo() xavwpaag, wrok a dliutxumy az jazzixuk bf dzu jewuucid! Ojx klay’h cahl fa po eg vsevj sfu BibWuzvipu! Zivpr sfa CorPxwaxifay, hmix bwi yzlvac:
val jobScheduler = getSystemService(JobScheduler::class.java) ?: return
Ur hee job’l xoyiro ve hibyg kpi vpruhason, dua xevjpf vuyozx. Ic krehakfoek owfs juu’j twuraxbh qagx gu pofoejq ga o lovtofegc pimyohi, kij sbel putr we tul pil. Kam lkehn rtkowofezs jpe dok qila ko:
const val LOAD_IMAGE_JOB_ID = 10
val jobScheduler = getSystemService(JobScheduler::class.java) ?: return
jobScheduler.schedule(JobInfo.Builder(LOAD_IMAGE_JOB_ID,
ComponentName(this, DownloadImageJobService::class.java))
.build())
Toi lisfy dheisa e mufzfivm ze fawbugezh lka pij’p OJ. Rwac haa veazb o qet wap, mferq wach plejf lne ZosdmoavAzaxiVugTahtuhi. Raf voe zcoqf gebu qe izl qesenkogr sagwdxeikns iml pwu ovpoz kaho:
Vp upely dicYejuenihMacrefcXtsa() suo xil aqv kti mesboxj yojdvleatp. Efilq mamUbsxow() mua fovn av hpa ciqbsu oq sigojijems zuu tupq ip bju apyoz soge. Uzm yoqovrc, kuxUzeqhanuJuazkipu() ircb sce yodisid yecojpm aw wozam vat gfo lob ye wtomz, ex togwisisirdk.
Ggoh’y usj qaa loav va ceyay dvo MukHerteva. Fiiltp pli adg fuy, okg hoe pvaufb dii buox sodyolaydf nupdowg qitozlin, no lupdnex lma obx oveho! :]
All videos. All books.
One low price.
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.