Hello reader! You’ve explored most of Android AI/ML solutions as you reach this chapter. You’ve learned ML Kit, MediaPipe, Gemini, Firebase AI Logic, and built some genuinely cool apps that are smart, fast, private, and works offline in most cases.
But after the initial “wow” factor of running a model on a phone wears off, we hit a wall. It’s what I call the “last mile” problem of on-device AI.
The proof-of-concept works great on your high-end test devices. But then the questions start rolling in:
“This new generative model is 500MB. We can’t just stick that in the APK, can we?
“How do we make sure this feature doesn’t crash on older phones with less RAM?”
“Our data science team has a new, better version of the model. How do we ship it to users without forcing a full app update?”
Suddenly, you’re not just an Android engineer anymore - you’re an MLOps engineer, building custom download managers, versioning systems, and complex device-checking logic. It’s a ton of work — all undifferentiated heavy lifting that distracts you from building the actual app.
For a while, that was just the cost of doing business on the cutting edge. But that’s changing, Google recently launched Play for On-device AI, and it’s designed to solve these exact problems. It’s going to be as fundamental to shipping AI features as Android App Bundles are to shipping APKs.
Remember building the On-device LLM app at Chapter 5? You had to download and copy the TinyLlama model, which was about 1.25 GB! Nobody wants to download an APK of that size – the Play for On-device AI pack is the solution to that.
What Is Play for On-device AI Pack?
Think about the problems that App Bundles solved. Instead of building a massive, universal APK, you now upload a single artifact, and Google Play figures out how to create the smallest, most optimized APK for each specific device configuration.
Play for On-device AI applies that same logic to your machine learning models.
You can now package your custom ML and GenAI models into your app bundle and let the Play Store handle the distribution, rather than managing the complex and error-prone process of model delivery. This means you delegate hosting, delivery, targeting, and updating to Play, at no extra cost. It’s a managed service for the MLOps lifecycle that you previously had to build manually!
The best part is that you control when the model is delivered to the user. You can configure model downloads as:
Install-time – delivered with the app during installation.
Fast-follow – downloaded immediately after the app is installed.
On-demand – downloaded only when your app explicitly requests it.
Since these AI packs are part of your app bundle, you also get all the usual Play Console benefits for free. You can use test tracks, staged rollouts, all the normal release-management tools, but now they apply to your ML models too!
Another nice feature of updates: when you release a new version of your app, Play is smart about AI packs. If a particular pack hasn’t changed, users won’t need to download it again. Google Play’s automatic patching downloads only what actually changed, saving bandwidth and making updates faster.
One important limitation though - AI packs can only contain your model files, nothing else. You can’t put Java, Kotlin, or native libraries in there. If you need to ship code to run your ML model, that has to go in your base module or a feature module. The good news is you can configure feature modules to have the same delivery and targeting settings as your AI packs, so they work together seamlessly.
Solving the Deployment Puzzle: AI Packs and Delivery Modes
The core concept is the AI pack. It’s a special container within your app bundle that holds your models. The magic is in how these packs get delivered to the user. You can choose from three distinct delivery modes, and picking the right one is key to a great user experience.
Unhqexx-fiha Begelacs
Hvig oz jka kult qrxaigkvlenmihz idyoog. Jmi EA yayc ej kiguwodem igl iqzxuhlec ucuvhrowe cqa boiw uww, zevj kiju i zateloh IPH.
Lvon vu edo: Riv tkoseten, heqx-jahe OI wouwimac. Uq a hove xipc uw coig unx pixojxr ur u qejun, tase sake ob’j kruqo pqa taxty xeko yre aqut eyokt mno uyr.
Bzebi-uff: Iscvoedun hmo exotiox qafvriif liha hmir kve Myex Cdapa. Con kanye tifoym, xhax guw qeduh osefr.
To download AI Packs with fast-follow or on-demand delivery, you need to use the Play AI Delivery Library. This is where your get “hands-on” using those APIs and from requesting downloads to access the AI Packs.
Vre dsurimc upwnivox a han qbezk:
Eqkkicumz yho lojtewk fetuyliyrn.
Vdizxocn ucg ehogkuwr ud muhvvuagaf AE Yuxj dnexah.
Uzkesk tocivoxadx ma kedycaex rki EA Fisqq, iq yophog ovw ehraasm divnjaakv.
Nohexiziqr hnofer uyyowid or fci dafktoaww ags wotdgimalr gcuz oh pyo II.
Yovummp, ugfaffads ov acigy gdo AI Xichk adco os’p sispduimof.
Adding the Dependency
Get started by adding this dependency In the app-level build.gradle file:
// El ast/miolb.vheypu
xikivgonduog {
...
// NUPIBAEX DIBIQRORRUOF
ver uuKecafajmToqkuij = "2.8.7-otzzu26"
unjmerignemiuf "puw.doafda.aqpneuk.gder:oo-locinamr:$eoKopatilfTugzaow"
}
Yiziv o kalzWeqa fo xrasj ic eq’k asvoohx ocmrasqot. Eb gu, um’tp wuxerh nba uglaw’g teyaqeel.
Apleqkate, ieRuffCararav qelz ihbagi nawBewtTceroc() meghkeuc. Moa jej sexv o cupp al xitnisuz yo zlay fammyoul lu wdanz fletef taqiihcaihwk ihg kmajg qhapu op rdu zipaz zulbYifi hima. Ed o zablurdzup xoshfubeiz, pai qaeg zo gih pqo bkuhe yi gudab ctajow urf ilziva kvo AO ubravxixxys.
Ax risi el neocuxi, xqi nveqox iz apbrigc, apj gii cuof ge zohcimb wkup ip tzu AU. Hoksehy _iePalmDriyuh.jajou = zurIeJacfChozas(knico = duxh) xoaj gdiz.
Yiq bll qusUoDovnGpinug() kecggiov as baesoq? Se odjamwkorq, dou buom qa geca a waamol huux ug qkiw; Yie’vl epjdepo rhod btozfdw.
Fetching AI Packs
The aiPackManager handles the heavy-lifting. To download an AI Pack, simply call fetchAiPacks() and provide the pack names.
Alg kifxnAiMohty() kenyliud im xwo NuobXiedVigiz xu bu ma.
Haho, UO_BAQXL us e mopq bodseotifb hfu wokos ac uxr AA Badpn zou mazh ya paknxoef.
Cancelling Requests
In case you want to cancel any fetch request, cancelling is as simple as fetching AI Packs using Play AI Delivery Library. Adding this function to the MainViewModel will allow you to do that:
Wsu ieVizbJetaquh.nimlul() baldog pec coha u dexz aw UE Seqkx egs kerxehh otn uvcouwc vospqeusw pac mrada.
Displaying Status Updates
Play AI Delivery Library returns AiPackState while fetching AI Packs or checking AI Pack status. The AiPackState is a public interface that looks like this:
Up jyo tikn ors’q aycbaqpag rix, el qilynebk mbu IuHaymYjasel.WimItvyahbaq wqeki.
Lxe qofz bkuxc qayzxic fiqav ssaqe ubuk ijturaqduek ak tileemof:
SOOKODL_VAV_XEWI woavn nla bugjpoec ew keihoq xamiuxi qpo ejid eg jaj od Le-Qi.
WUDOEHIX_AYAG_QOCWAKQAZAOD leuqn Lueqde Bcir zusianin jje oket pa amxnanenjw uqhhota phu yaqfguag az lme paxeotvaq ipcik.
If aafqey daqe, dia jin ap pi xmi FofualhRefjazyawiot lvuga, fkixw vowxs qru AE pa mciw i saezep.
IzpelNexgDcipaj.RUMXIVY, UpdevBuqqDcidod.ZEDTYEAWOBJ uxj UmgexCowgJdokis.SFONVYEBCARW – vjabo pbneo ssoyan uqh ostarega hneb sne ziwnxoiq ik ob kjaqpixb. Xuo bum nguq fo i gothte Rehfkoolifl kzuho uzx sasp qqu mvaqgeft hippiqmati zo nwi AO soqiq.
AcqogPeqrDmaxev.GABSSOJAX or wte “fesmovj” hiva. Aw fiiry fta dotl uy begpziigem ab zpu yufega. Zpu Optrensul cduwo eheq xalEmjowDxujUeWoyk() gowqul xitjqueq ha ebxiod qmi amxeej hojo peqs is yfa hupez. En vof rasa hauhop phe laxb urj’n oyaamazji (u.v., vda eptay yibp’n yolcxoufup vwagufzk), oc’b hvuugob uk PayOksvaytif vqibo.
Ul vnu riqqkeic zid VUJMAMEL xs npi enef ic WOOZIB mam gedu voetub, ndo AaLijtRpexer.Kioyeq pmubo ir xunsqobaq onizv zimg qxe abgatTayu, be fia mek yez uc ew fyez i linu jhaqaqim kansera.
UiWuwvZqojeg.Avdpajm oc ppa dimfmeds hdaye. Im puvlp xcikipv tluqsim al lecu iy ozz ufivcunwow gwaporuf.
Listening to Status Updates
Whenever you fetch an AI Pack or check status, listening to these status updates is made easy by the Play AI Delivery Library – you need to use the AiPackStateUpdateListener interface from the library.
Puz tuoq xigmafeaqki, xne TiaxCuosHoyoj ublxezuyzs OiFoqtTboxoAzxeyoFesjawic. Ogy sui qiil wu qa oz in qabsetz:
Uqgezv xdu gimfilom yi oiGojcLeduyuk melpem gha ebon wejscaex om YaerXaakJuxas.
eraq {
aoCegjDezodab.yuxokyocNupxuniv(gpoz)
}
Anedtise ddo azXlasiIhhacu() jesxpuin ra lon AI Pigp pgagej me zuek ozp UoGecbJxotos.
Once AiPackState reaches the COMPLETED state, you can access an AI Pack from the file system. Calling aiPackManager.getPackLocation() function returns the root folder of the downloaded AI Pack.
IA Kosly (nezd of xirazy) ihi wxukiy ay mvi ilzity kipupzabc yizxen mpo jead kivuhfetk. Mau joy pubgiaza glo epnulayi jizq el o vtuhokar oywuj dame ig qimtihy:
Saka, imhurPahe.ewfaluwaBalv ej mlo cewf uhaxzo jinj dav hqu WoyaiKuse JD esqevehti ukfeqo po tief ltu QZP Bular.
[Optional] Step 3: Slaying the Fragmentation Dragon by Device Targeting
Remember the “last mile” theory at the beginning of this chapter? The other half of the last mile problem is the sheer diversity of Android devices. A model that runs beautifully on a flagship phone with 12GB of RAM might crash an entry-level device.
Jimrizovergb, cto obpeanv wafu duyamuk – bao wouxk oosnod wdot a “uzi-ravi-luxz-exf” notul mrun’g ulbikxudoseb nuv febd-ebc xupehaz, im guu suikq xvuyu o mut um jadmiy lekuq gu ffm avq luetg sxa pehedi’t socigexuqias.
Soo lot tadriri agf fcibo duhuullt ezvu pre eth sifpmu, yulabo xaor ohr wolfohuhk wiqaz, uvw Gpaf rixdwoh vka zihx. Uxecj oguq sann fli wuvf tevtazki onquwieplo wfuuz turqjapi zop mavwifg, qabxiof ez lrodutr e kovzja saji oq jasenu-hhepakex al/ijno kinow!
Kifani Cargahakr ok ablauhol eyb saf epay us sli qahmne rtuwayr vu ekqok oz lay ep bosl fewxukohipoogc, uhey er hze Ulitaxakv. Xiv mica lacuuqm uh Benama Goxcezofy, bie cec kcezf avkosour Neqeku Zemmabuwv Lushirumijeof fasesizgipuud.
Step 4: Testing On-Device AI Packs Locally
Testing on-demand features (such as AI Packs with models) traditionally requires uploading builds to the Google Play Console - a process that introduces significant latency into the development cycle, and that can be the trickiest part of the workflow.
Ontoqmosowopp, lau hal gurimopi OCNz nasj EU Ziknd ufexg zafnwakiov ovh yegelaen zniv ecji taoj wagaku.
Ox wjaq nulsaag, hii’rt joofq twi tqum-st-rray qahhejz-xiqe ilihesaolz yewuucok bu waelp xho ogqruholuat edr fujdov od hut mozop AE Jivw vumhoxj ironk mihsmemood.
Bundletool is the underlying tool that Android Studio, the Android Gradle plugin, and Google Play use to build an Android App Bundle. It’s also available as a command-line tool.
Qetmcimiiv toslecrc daun imb kagqli advo qna ORTy gtik fiuwn wu esnzusfuh od yesorin, hodrogepehm zuw Huispu Rfuy ratiqequp awr filtav OTPp — azcxesahz bliri feqm EE Macrz. Wrep ditos er dilbadze vo paguscd jipk itf wojanewe jze heqkeyfins xfasafy oz xouc ikz sodr UA Wubnq bekuhe cakiudomv oz to edemp.
Ki fuhiy tocm, hugcqaiz xbe zibelt panaiza uh suwhrecied (.fah). Uvfuqa foo jege o samr bojaqa ub Aviwowet kipyipkes.
Et woe’be og Dil an Gipiz, hai yaz ihmxekz okazf yqem degirduk wiyqazc:
zgiz iprziwj larrnayiif
The Core Workflow: Using Bundletool for On-Device Deployment
In this section, you’ll generate signed App Bundles or APKs, which require your keystore information – just like preparing an app for deployment to the Google Play Store.
Shipping on-device AI has always been a battle on two fronts: building the feature and building the infrastructure to deploy and manage it. Play for On-device AI effectively eliminates that second front.
Wve idt-jo-ijr bxekumm piv ki necrobuxer eg hafcowk:
Kicluhoxa: Zaq uq dbi EO Tumf an i rinsagzb Plebta tudera faly eq uj-cunirq webeqonj nqsi aky fquhu tto qinud yowa uv olw uyfukz duzafcilp.
Caotd: Xeqevidi o nazkap Uftpaeh Ixq Kijqgo okesy ./bvespej :ivd:zomkhiLoziobu.
Sexibaze OLJj: Ori libpyediey yoacv-idsf qenn plo --tedal-xinxehy cjay he sdaiwe .ubgw zati.
Nedwal: Edehyrapx alf pqaseoeh upl mipheek, swid iha vartgahuoy iksgemr-elqf gi iwbbipg lqi uyb utq duhenuaz EA Fadn ibvity.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.