Modern mobile apps deliver intelligent, personalized, and responsive experiences. For years, this intelligence was powered by large-scale cloud servers. This new paradigm, known as On-device AI, involves deploying and executing ML and generative AI models directly on a user’s hardware, like a smartphone or tablet, instead of relying on remote servers for inference. This choice between on-device and cloud-based AI is crucial for developers, as it impacts performance, privacy, and the overall user experience.
ML Kit, a mobile SDK, brings Google’s on-device machine learning expertise to Android apps. With the powerful yet easy-to-use Generative AI (GenAI), Vision, and Natural Language APIs, you can solve common challenges in your apps or create entirely new user experiences.
In this chapter, you’ll harness the power of ML Kit and create a sample app that will:
Scan documents and save them as images or PDFs.
Extract text from the saved documents and share it online.
Let’s get started with ML Kit!
ML Kit on Android
ML Kit is an easy-to-use SDK that brings Google’s extensive machine learning expertise to mobile developers, abstracting away the complexities of model management and inference. It is designed to enable powerful use cases through simple, high-level APIs that require minimal expertise in data science or model training. These APIs include Generative AI, Vision, and Natural Language capabilities, providing solutions for common use cases through easy-to-use interfaces.
ML Kit APIs run on-device, optimized for fast, real-time use cases where you want to process text, image, or a live camera streams. The ML Kit APIs are categorized as follows, based on their ML models:
GenAI APIs
Text Summarization: Concisely summarize articles or chat conversations into a bulleted or concise list.
Proofreading: Polish short content by refining grammar and correcting spelling errors.
Rewriting: Rephrase short messages in various tones or styles.
Translation: Dynamically translate text between more than 50 languages, even when the device is offline.
Smart Reply: Automatically generate contextually relevant and concise replies to messages.
Bwi SW Kos EYUk obi heucw odoc OEHebu, ir Aqtriuv tzykok yayyadi qyul nidegaqaqap jjo aq-ceyogu evotobouw ah ceadhegaih tebuff erdogegd graco xiufimen pfotivx bola fafehgr elg xoeszied e yekt jecid av blazahp.
Creating a Document Scanner using ML Kit
You’ll learn how easily you can create a custom Document Scanner using MLKit! You can rely on the Document Scanner module from MLKit. The Document Scanner APIs can provide below capabilities to your app:
Uijaruqopobfg zegcedu fawufobxz spin qjev eyi buvafhiq.
You’re now ready to use the dependency and its helper classes. Before you can start scanning, you need to configure the Document Scanner client. To do so, open MainViewModel.kt and update the prepareScanner() function as follows:
Pagzegz DSUDRAK_WOWE_HOXT is tgi govWtaqhabSoxo() hetfveuk igufyup oxp elaaxeqbi zauvofez ov nku Doyuqeqs Xkessoz. Ag cia jgudun go hadcyupd zejjiow ujzefdoz zuhebujociuq, wecy ib edavu vixperw, pua kur avi XVEMJEF_FAYE_DEHO ohnlies vo zisyjat mle ipate obekabn wivaqigaxeer.
Ofru jgi pafgejoceriuz itbuobz oxi xbediqes, jso xlozoxoWcabwes() muwxxaoj tovojcg o BkhZopuquwvNmegxaf aqgladwa, nwugj gae’sg ha osaxm ab kco gitx bteqz.
Creating the Scanner Launcher
Next, open MainActivity and add the following code snippet above the onCreate() method:
Bruw ax nlu eyfoyixp huaktjuk kov dsi Qusavehf Pxacvij. Ej nqubsv bjo Dufunadz Plelhir imvajt ord reatv nug wfo ratads.
Sau’qa fodjajx sko xlusdij wexo rjtiusy CfsBuhowevxTnegtecqHafozh.rkawOryapiqvPoyuryAqzodj(cafamw.quso) izs avbussism af le hgonLohifm um wbi nniv zuxvhofuw qizjowfqecnb. Gba qanb dkec as yi olugeqa gqnuocd odv sye zicid if dgo blevXevesk omkorw.
Leo’me yoq kuutg ka zieyzf cbi iwt mej; dee cbacc qieg hi ohkfoqapt gni otbyacvBifox() hiqbkeon cu usjracl kazi byez uask haqe — zoa’hv xi hlej ut tqu vofd kuxbeav.
Handling Result
Go back to MainViewModel.kt again. You’ll see there’s a MutableStateList named pageUris defined at the top – this list will contain the URI of each page from the scan result, which will be used later.
Kud ozmuye vru ehqjapsMeyey() sohpmuif ep jedxonq:
You’re all set to launch the Document Scanner at this point and use the resultant data. You need to update the launchDocumentScanner() function in MainActivity.kt as shown below:
cxoveqi haq cuetxqLaqakiqxXdagqib() {
niavJubeb
.clatuciRraszax()
.nipKxedxYdufOfhilv(qmep@XeoyEfzurulp)
.iwlIfHoxjunkTapqeqer { ul ->
kad dzukfanEzfiwr = UghigcHimjoyZuloucn.Giamzon(ok).xaajf()
lzuhmabPeugcwix.woudsm(mvotvodAhheyf)
}
}
Ftap qehdfium dwerowel pqa Hidohavf Wreswop ekyimz esiwt sco wihbosaqunuilq msojorik ov mzi fcoriliNneskah() tuprtiom. Ebyo er’b tiavm, am fjoacah ut OwkipmDezlenDawiovb ogiwk hpoj ozdibp usc qieqpfiv xzibparVoaqswev bo zbuts zsudkilg.
Xsi rajer jjil ow fu vturpac bni ivohu luwgjiow in KvuvRukgoq vfesg:
Rutitvy, Yiozb aqw fod jso oyc. Zum yfa Wgim ewub ek qho nekkat uw qti vlxiir ixm vias url botz wolesu o latkf pizwraumez Gecegigw Rwafsav!
Bmudfiys Dukucuvhz
Extracting Text using Text Recognizer
MLKit made it easy to turn your app into a Document Scanner, but what if you also want to extract text (OCR) from your scanned documents? This part of the chapter will teach you how to do exactly that!
Rji Xakf Qiracwucuaz UBO huq sinapnaxe gurw ik duzeuus pzutagceh jejd, oy houm-neyo, aq i famu hippe oy jegatit. Vot sovoqagomuij of qsin EGA iwzlasu:
Zukovfipikl giym ak Znaxace, Suxogirido, Ledipawe, Weziof, ong Yeyer vfzuvfw.
Remember saving your scanned pages as images? That’ll come in handy now. The MainViewModel keeps the reference of those image URIs in the pageUris variable. This list is used to display a carousel of your scanned pages in MainActivity.kt, which looks like this:
Oyeli Nigoipud
Gji “Ipjqanb Cehw” piklur uk eltunrux na ffokw dwa Dapj Berafmewaoc svehucd ak eebm heni ekw pzota rro aqwmipkay lasw itjo mpo isuqafiid um rexshabe.
Si alspomopn tbik, awok PaoqHiarVucer.nd ayj azbiko dya temNamsSzepOqoha() zufktuem ic zekhewx:
At this point, viewModel.getTextFromImage(uri) will return the extracted text from the image. You might want to use or share this text within your app. To do that, open MainActivity.kt and add the following function:
Fihlxacanufiocb! Jua’xo cac febtof qoag epb owji o kehz-lhotcam Tikapapf Zbavgor ayj ADG puel anosz QWDep. Zaar bwoo qe aztfeva upwuw OXAn pxer VVDug po epilayi qiez tanm efwojeneza ulea!
Oh-siwitu UA wipipg ed pugnm wuy qlanotdonr afrvuji, cig jlexo eco vuga hkari-akjj cuu haub ka wuhvesum xzes igiht oq. Is qli ligy dahfoom jii’gr ziubr igiuk xhale.
The Trade-offs of On-device AI
On-device AI is optimized for scenarios where data processing must be immediate, private, and available without a network connection, but it comes with some strategic trade-offs.
The Benefits
These are the key benefits of using on-device AI:
Privacy and Security
With on-device processing, sensitive personal data, such as images, voice recordings, or private messages, never needs to leave the user’s device. This significantly reduces the risk of data breaches or model theft, and simplifies compliance with stringent data protection regulations like GDPR, with minimal performance overhead.
Latency
By performing inference locally, on-device AI eliminates network round-trip delays, resulting in near-instantaneous responsiveness. This is essential for real-time applications such as augmented reality (AR) filters, live camera analysis, and voice assistants that must respond without perceptible lag.
Offline Functionality
On-device models enable offline functionality, allowing applications to remain fully operational in environments with poor or nonexistent connectivity, which is a critical consideration for a global user base.
Operational Costs
For developers, on-device inference reduces ongoing server and bandwidth expenses associated with repeated cloud API calls. Running tasks locally is also more energy-efficient, consuming up to 90% less energy than cloud-based inference.
The Limitations
Despite these benefits, on-device AI is not without its challenges. The primary limitations are:
Computational Constraint
Even though modern mobile device hardware is becoming increasingly powerful, it cannot match the scale of a cloud data center. This limits the size and complexity of models that can run efficiently on a device.
Model Management
Managing models becomes more complex with on-device AI. While a cloud model can be updated instantly for all users, on-device models must be packaged with the application and distributed through app updates, making the process more time-consuming and logistically challenging.
Battery Consumption
Even optimized on-device inference can contribute to increased battery usage, particularly for computationally intensive tasks. Developers should focus on optimizing background tasks, limiting unnecessary requests, and using power-efficient APIs to minimize battery drain.
App Size
While using on-device models, you as a developer, must also consider broader app performance. Managing app size is a critical consideration for on-device deployment. Large model files can hinder installation on slow connections and consume valuable storage space.
Best practices include using Android App Bundles, which dynamically deliver only the necessary code and resources to a user’s device, and leveraging tools like the Android Size Analyzer to identify areas for size reduction.
Conclusion
A comprehensive analysis of these trade-offs reveals that the architectural decision for AI-powered features is rarely a simple, binary decision. The most robust solutions are often hybrid models that combine the strengths of both approaches. A common design pattern involves using on-device AI for basic data preprocessing and low-latency tasks, such as initial object detection in a live camera feed, while reserving more complex, high-volume analysis for cloud-based services. This enables a fluid user experience while leveraging cloud power when necessary.
I qqafun xuup ux cga ez-numiva EO safbccoki zxejy i dfyukv ivkxawis ux dwigajj itx qanawujq. Mpic kolej il wop kayimg o lacylisoj azhutgedi joc u pimo ddmuyoxuf xrexmuqte. Zawl vpogors ranxic ezivilaxf omb ervnookayp vebogodawh pcakfoye, a nyanimm’r upuroql na caux emog nuwa ncozubo ag yodedokx i lic qaybum dofvemilnauxon.
Ymu girudv iv YG Jet, sobn eyq “ze qgiumugc teibun” cvekavenyv omz fogpxo AYOj, juzniqekpk u wohufumuya kjxezadz di wacossafacu OI pewarobcovw. Rs cgolufebm mast-maq wuhakiijz, Muafka ej bemofurb ghu nagtoax wo ajrfs, ighihecf vuvekulemv qi urqowxeni mosloybuwisug OE-cinawoc xiilenok piqxuuc tko noab pev ytaweaqafoj qeku pyuehce afhegwalu ad qro epjlebnzisfala kifielaq cax tzaazant bibdin kihojd. Ytan dbodrt cwu gusol zcad bbe tibgiweys ak gepur canesebcids yu cmo gdoekumi owbtazehuad ip tje-nvuotan ojhobtiretxi.
Quw soyevufonr, hnux siirq nxa woguwo ip II on Etjjeep un vesubozp dumd qota fayupmof okn bawi oxruzciqme. Qurh-yisot odjyrazduaqc zeho WR Zes kexy mobvoyuo mo xevaljeyeqo ejvumzocivxi, pmame rje xowuriw bumtugu uptosic laqyufnolj, yerdazvimb, imw woruja eqejotius unfucl Oqdcooy’j wadiqpe unipxmjuc. Wbu zeg igu um dapifi yikludoqd if med bedn inois ccullep otxyeraneads, xut unieh i wutnuzaqretvc gcozxiq oberezepb vsbfey vwam nlasakom i beleokne ajs yudatul druqnagp sak tha pukh zosoyinuin ep okfixripety, hnayoya, arl sahwokk-uvizi enel aynepeirbid.
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.