Recent Posts
Archives

Posts Tagged ‘Android’

PostHeaderIcon [GoogleIO2026] Android accessibility updates

Lecturer

Yvonne Ellefson is a Program Manager on the Android Accessibility team at Google. She collaborates closely with the disability community to shape platform features that improve everyday device interaction. Isaac Chai is a Software Engineer on the same team, focusing on Voice Access enhancements, large-screen behavior, and developer-facing accessibility APIs and best practices.

Abstract

This article surveys the accessibility advancements presented for Android in 2026. It covers AI-enhanced TalkBack capabilities, refined system features such as expanded dark theme and magnification, Voice Access usability improvements, and concrete developer guidance including scalable-content gestures, magnification API adjustments, semantic labeling practices, and the deprecation of announcement APIs. The analysis emphasizes how these changes, developed in partnership with users who rely on assistive technologies, raise the baseline quality of experiences while placing clear responsibilities on application developers.

Platform Feature Enhancements for Users

TalkBack receives substantial upgrades powered by Gemini 2.5 Flash. Image and screen descriptions become more precise and reliable, supporting 38 languages so that users worldwide can obtain context for unlabeled web images or personal photos in their preferred language. Two distinct text-to-speech voices address competing demands for speed and naturalness: a highly efficient voice paired with an announcement cache reduces typing latency by 37 percent, while a high-quality natural voice improves long-form reading on recent Pixel devices (Pixel 8, 9, and 10). A two-finger double-tap gesture initiates dictation and automatically reads the transcribed text back for verification. Physical-keyboard support expands with an enhanced keymap offering more than 100 new commands that treat the Action key as a dedicated modifier; browse mode gains single-key navigation. Braille keyboards and displays become customizable, allowing users to map gestures and buttons to their preferred workflows.

Expanded dark theme functions as a system-level fallback that automatically darkens applications lacking a native dark theme, reducing light sensitivity barriers. Users can disable the feature on a per-app basis when results are unsatisfactory; developers remain strongly encouraged to ship official dark themes. Magnification now supports zooming the on-screen keyboard—valuable for distinguishing emojis and symbols—and can be controlled by connected keyboard and mouse. Keyboard shortcuts provide rapid zoom control, while mouse-following modes (three variants) help orientation and mitigate motion discomfort. Three-button navigation button order can be rearranged for one-handed comfort; the preferred layout migrates with device setup from a previous handset.

Voice Access simplifies activation through a unified accessibility shortcut that controls listening mode and appears automatically as a floating control. Alternative triggers include volume keys, accessibility gestures, or the navigation-bar button. Once enabled, “Hey Google, start Voice Access” launches the feature hands-free via Gemini; “Stop listening” pauses it. Text-editing commands improve recognition of punctuation and support replace/delete operations (for example, “replace apples with kiwis”). Privacy defaults keep Voice Access off during calls, yet users may enable continuous listening or automatic activation for incoming calls. Speech recognition accuracy rises and Japanese language support is added. On large screens, number and label sizes increase and a coarser grid reduces visual density; commands apply only to the foreground window, preventing accidental interaction with obscured content.

Additional recently shipped features include Fast Pair for selected hearing-aid partners and Guided Frame on Pixel cameras. The latter uses AI, audio cues, and haptics to assist framing; offline scene description now covers more than 50 languages (20 on-device), delivering real-time descriptive feedback even without connectivity.

Developer Responsibilities and API Guidance

Many user-facing improvements depend on thoughtful application support. Dark theming remains the preferred path; expanded dark theme is a safety net whose heuristics may produce imperfect results. Developers should test thoroughly on devices running Android 16 QPR2 (API 36.1) and later.

A common library now standardizes pinch-to-zoom gestures for scalable content, allowing users to adjust text and UI element sizes intuitively. In Live Transcribe, more than 94 percent of font-size changes after the gesture’s introduction occurred via pinch rather than settings menus, demonstrating user preference for direct manipulation. Compose integration follows published tutorials.

Magnification reliability with keyboard and typing interactions requires additional information when calling requestRectangleOnScreen. A new overload (API 36.1) accepts a request-source parameter indicating whether the movement results from focus change, list scrolling, or caret repositioning. Built-in components handle the parameter automatically; custom views that invoke the API directly must supply it.

TalkBack’s automatic image descriptions continue to improve, yet developers retain primary responsibility for high-quality, localized content descriptions. When user-generated images prevent static labels, correct semantic declaration is essential: use or extend Image composables in Compose, or ImageView / ImageButton (or subclasses) in the View system. Custom views should override getAccessibilityClassName to return android.widget.ImageView.

Accessibility APIs continue to evolve toward richer, technology-agnostic semantics and away from service-specific behaviors. Accessibility announcement APIs, deprecated in SDK 36, are scheduled for eventual removal of TalkBack support. Developers should migrate now. Recommended alternatives include descriptive action labels that eliminate the need for confirmatory announcements, window and pane titles that TalkBack announces automatically on transition, and live regions for transient or updating content. TalkBack’s speech-output overlay (developer settings) highlights announcement-driven feedback in red, aiding discovery of remaining usage.

The Accessibility Scanner receives an update that detects missing labels, undersized touch targets, low-contrast text and images, and other common issues. It serves as a rapid check during development or pre-release, complementing—but not replacing—manual testing with actual assistive technologies. Official developer guidance on testing remains the authoritative reference.

Collectively these platform and tooling advances lower barriers for users while clarifying the semantic contracts applications must uphold. Developers who implement native dark themes, scalable gestures, accurate image semantics, and modern alternatives to announcements contribute directly to an inclusive ecosystem capable of serving the widest range of abilities.

Links:

PostHeaderIcon [GoogleIO2026] What’s new in Android

Lecturer

Nick Butcher is a Product Manager at Google focused on Jetpack Compose and Android UI, based in London. He previously served for over a decade as an Android Developer Relations Engineer, contributing extensively to Material Design advocacy, open-source projects such as the Plaid sample application demonstrating advanced animations and patterns, and official Compose samples. His work bridges design and engineering, emphasizing productive toolkits for native interfaces. Ash Nohe is a Senior Android Developer Relations Engineer at Google specializing in core OS experiences. Daniel Galpin is a Developer Advocate at Google, known for covering platform updates, performance, media, and ecosystem topics through technical writing and conference presentations.

Abstract

This article examines the principal announcements from Google’s overview of Android platform evolution at Google I/O 2026. It analyzes the formal shift to a Compose-first development model, performance and memory optimizations introduced with Android 17, the integration of agentic AI capabilities that reposition Android as an intelligent system, and the expanding multi-device adaptive ecosystem spanning large screens, Wear OS, XR, cars, and desktop experiences. The discussion situates these changes within broader industry pressures around hardware constraints, developer productivity, and user trust, drawing solely on the presented technical details and case studies.

Compose-First Development and Tooling Advances

Android’s recommended native stack—Kotlin, Jetpack, and Jetpack Compose—has matured over five years into the preferred foundation for building performant, device-optimized interfaces. The platform team now positions Compose as the standard for all Android UI work. New platform APIs, libraries, tools, and guidance will ship exclusively for Compose, while view-based components and related libraries (Fragments, RecyclerView, Material view components) enter maintenance mode. They will receive only critical bug fixes; no new features are planned. Existing view-based code is not deprecated and may remain, yet teams are encouraged to migrate screens to Compose when touching them in order to gain maintainability and performance benefits.

Compose 1.10 and 1.11 introduce substantial capabilities. The experimental styles API standardizes styleable attributes, separating component anatomy and behavior from visual appearance. It supports state-driven styling with built-in animation of state changes and automatically minimizes recompositions for performance. Future Material component support is planned. Shared-element transitions, text-field enhancements, the retain API, and more deterministic testing APIs further strengthen the toolkit. Performance gains appear across common user journeys—scroll jank, startup speed, and hybrid View-Compose UIs. Open-source benchmarks comparing real-world View and Compose implementations corroborate these improvements; most gains materialize simply by adopting the latest Compose version.

Production evidence reinforces the technical claims. TikTok reported that expressive Compose APIs enabled rewrites that improved maintainability while reducing page-load times by 20–30 percent, with one case achieving a 78 percent speedup. Complementary tooling accelerates migration: Android Studio agents will soon leverage project-specific knowledge of styles and resources, and generate screenshot tests to validate visual fidelity after conversion. An existing skill already assists XML-to-Compose translation.

R8 remains central to APK size and runtime efficiency. New Play Console insights surface optimization opportunities, while the R8 configuration analyzer scores obfuscation, shrinking, and optimization effectiveness and flags overly broad keep rules. Tinder, already invested in R8, removed a single problematic keep rule and realized a 28 percent APK-size reduction together with lower ANR and cold-start rates. Grab’s nine-million-line codebase similarly benefited from R8 enablement (25 percent fewer ANRs, 16 percent smaller APK, 27 percent faster startup after baseline-profile work). A new skill equips AI agents to work with the analyzer, lowering the barrier to effective configuration.

Memory, Performance, and Platform Foundations in Android 17

Rising hardware costs and constrained RAM supply elevate memory efficiency as a first-order concern. Android 17 introduces memory limits that primarily affect apps exhibiting runaway leaks or excessive consumption; affected sessions report “memory limiter” via ApplicationExitInfo. Profiling Manager gains anomaly and out-of-memory triggers that yield app-specific heap dumps, alongside cold-start and excessive-CPU triggers. LeakCanary integration inside the Android Studio Profiler, augmented by Gemini explanations and fix suggestions, accelerates diagnosis. Play Console will surface memory telemetry, and Studio will receive smarter debugging tools, preparing developers for stricter platform policies later in the year.

Platform-level improvements complement app-side efforts. Image and notification custom-view sizes are restricted; oversized content is stripped. ART’s garbage collector adopts more frequent, less intensive young-generation collections, improving both memory behavior and performance; these changes reach more than a billion devices via Google Play system updates. Targeting Android 17 disables reflective modification of static final fields, enabling more aggressive ART optimizations. A lock-free Android message-queue implementation reduces UI jank and yields dramatic speed-ups (up to 5 000×) under high contention.

GPU strategy centers on Vulkan as the native API. OpenGL and WebGPU layer atop it; ANGLE translates OpenGL commands for apps not yet migrated. An idiomatic Kotlin WebGPU Jetpack library lowers the barrier for managed-code environments. Adobe Premiere’s forthcoming Android app already employs WebGPU with Media3 Transformer for template-driven Shorts creation. The Android Performance Analyzer unifies system-wide insights, loading and rendering traces up to 26× faster than the prior GPU Inspector while preserving broad compatibility. Partners report concrete wins: Netmarble cut GPU usage by up to 90 percent in The Seven Deadly Sins: Origins; The Forge reduced per-frame CPU cost of key Vulkan APIs by up to 50 percent.

From Operating System to Intelligent System: Agentic AI and Proactive Experiences

Android is evolving beyond a conventional operating system into an intelligence system that anticipates user needs. Next-generation autofill improves form-completion rates using existing hints. On Pixel devices, AI detects scam patterns in messaging-app notifications and warns users before they respond. Magic Compose, introduced on Pixel 10, surfaces contextual information and actions inside apps and is expanding to additional titles such as Snapchat, creating new discovery surfaces.

The agentic era enables assistants such as Gemini to orchestrate multi-app workflows. Gemini can analyze screens, navigate tasks, and pause for user confirmation at sensitive points (for example, transactions). Background execution occurs on a virtual display, allowing the user to perform other work concurrently. App Functions—a platform API and Jetpack library—lets applications expose capabilities as on-device MCP-style tools. Apps that already separate data and presentation layers can integrate relatively straightforwardly. A demonstration with the Now in Android sample automatically generated functions for listing topics and articles, following topics, and bookmarking content; an accompanying test agent and live Gemini instance executed multi-app flows (retrieving an article and sending it via a separate chat application). Early-access programs invite production deployment.

On-device models such as Gemini Nano, available on more than 140 million devices and based on open Gemma models, keep data local, function offline, and incur no per-transaction cost. Gemma 4, expected on flagship devices later in the year under the Apache license, improves multilingual support, battery efficiency, and advanced capabilities. The AI Core developer preview and ML Kit prompt API already power production features: Webex translates short chat messages; Photoshop explores automatic layer renaming. Cloud-side Gemini via Firebase AI Logic supports more demanding workloads, illustrated by ABC Mouse’s closed-loop personalized support for children. The forthcoming ATUI protocol and Jetpack Compose renderer will allow cloud agents to display rich client UI.

Privacy and security foundations underpin these experiences. Android 17 enforces read-only native libraries on dynamic load, delays most apps from reading OTP SMS for three hours, and extends Credential Manager with verified email/phone verification and automatic passkey creation for existing password users. Health Connect gains cross-app data-sync requests; Companion Device Manager unifies association and nearby-permission dialogs with medical-device and fitness-tracker profiles. Access-local-network permission is now required for LAN discovery. Privacy-preserving pickers mitigate broad-permission requests: Output Switcher for Cast devices, an eyedropper API for single-pixel color sampling without screen-capture permission, refined Contacts picker for selected fields, and an updated Photo Picker supporting portrait grid view.

Media and camera capabilities expand correspondingly. On-device image and video enhancement libraries (used by Instagram) apply upscaling, deblur, denoise, and tone mapping entirely locally. Audio APIs are restricted to foreground apps and appropriate foreground services, reducing unexpected background capture; MediaSessionService mitigates impact for legitimate background playback. Support arrives for new professional image and video formats, improved HE-AAC streaming, vendor camera extensions, and next-generation Eclipsa HDR video with ExoPlayer integration. Picture-in-picture receives a dedicated Jetpack library usable with CameraX for scripted recording workflows. Live Update notifications gain a metric-style template and semantic color API; call history is unified across telephony and messaging apps; system emoji become richer while remaining zero-effort for developers who already use system emoji.

Adaptive Multi-Device Ecosystem

More than 580 million large-screen devices are in use; users of these form factors engage more deeply and expect full-screen utilization regardless of orientation. Android 17 therefore ignores orientation and aspect-ratio opt-outs on large screens. Navigation Free and Compose adaptive libraries handle common scenarios; Navigation Free 1.1 adds scene decorators for global navigation chrome, and 1.2 alphas introduce deep-link support. Experimental Compose 1.11 APIs—MediaQuery for capability interrogation, Flexbox for responsive growth/shrink/wrap, and Grid for structured rearrangement—further simplify adaptive construction.

Wear OS 7 delivers up to 10 percent better battery life. Phone media sessions automatically surface system playback controls on the watch; live-update notifications can be bridged by manufacturers; local live updates serve phone-free scenarios. Wear widgets evolve under Jetpack Glance (tiles become widgets); Remote Compose enables expressive animations. A Wear workout tracker arrives in Google Play services; Compose for Wear OS 1.6 adds Navigation 3 and ambient-mode management. The Wear OS 7 Canary emulator is available in Android Studio.

XR headsets and glasses inherit adaptive work. Immersive worlds can be generated procedurally to keep APK size modest; geospatial navigation aids wired glasses; Godot and Unreal Engine support expands with vendor extensions (scene understanding, light estimation, face tracking). Jetpack Compose Glimmer gains interactive lists and stacks plus an agent skill for rapid adoption. An XR Developer Catalyst program provides hardware, resources, and funding.

Car development benefits from increased parity between Android Auto and Google-built-in systems. Car App Library templates now cover media on both platforms; Maps with Content template and the Google Maps SDK are shared. Version 1.9 introduces ten flexible components (enhanced chips, expandable headers, progress bars) available via early access. Parked-to-driving transitions and equivalent video experiences (HD while parked) are scheduled later in the year.

Desktop experiences gain relevance with Google Book, the next Chrome OS iteration built on Android stack components. Adaptive apps that already support keyboard shortcuts, drag-and-drop, and custom pointers (examples include Brand Lab, PowerDirector, Notability) deliver improved desktop-class behavior.

Taken together, these initiatives reposition Android development around a productive Compose-centric stack, rigorous performance and memory discipline, agentic intelligence that keeps apps at the center of user workflows, and seamless adaptation across an expanding device continuum. Developers who adopt the recommended practices and early tooling position their applications to deliver the high-quality, trustworthy experiences expected by the platform’s diverse user base.

Links:

PostHeaderIcon [KotlinConf2025] Build your Kotlin and Android apps with Buck2

Sergei Rybalkin, a software engineer from Meta, introduced the audience to Buck2, an open-source build system that is now equipped to support Kotlin and Android applications. In a concise and informative presentation, Rybalkin detailed how Buck2, a successor to the original Buck system, addresses the need for a fast and scalable build solution, particularly for large-scale projects like those at Meta. The talk centered on Buck2’s core principles and its capabilities for accelerating development cycles and ensuring consistent, reliable builds.

The Power of a Scalable Build System

Rybalkin began by outlining the motivation behind Buck2. He explained that as projects grow in size and complexity, traditional build systems often struggle to keep up, leading to slow incremental iterations and hindered developer productivity. Buck2 was designed to overcome these challenges by focusing on key areas such as parallelism and a highly opinionated approach to optimization. The talk revealed that Buck2’s architecture allows it to execute build tasks with remarkable efficiency, a crucial factor for Meta’s own internal development processes. Rybalkin also touched on advanced capabilities like Remote Execution and the Build Tools API, which further enhance the system’s performance and flexibility.

A Blueprint for Optimization

The presentation also shed light on Buck2’s philosophy of “opinionated optimization.” Rybalkin clarified that this means the system takes a firm stance on how things should be done to achieve the best results. For example, if a particular feature or integration does not perform well, the Buck2 team may choose to drop support for it entirely, rather than provide a subpar experience. This selective approach ensures that the build system remains fast and reliable, even as it handles a multitude of dependencies and complex configurations. Rybalkin underscored the fact that the open-source version of Buck2 is almost identical to the internal solution used at Meta, offering the community the same powerful tools and optimizations that drive one of the world’s largest development teams. He concluded by encouraging the audience to try Buck2 and provide feedback, underscoring the collaborative nature of open-source development.

Links:

PostHeaderIcon [KotlinConf2025] Code Quality at Scale: Future Proof Your Android Codebase with KtLint and Detekt

Managing a large, multi-team codebase is a monumental task, especially when it has evolved over many years. Introducing architectural changes and maintaining consistency across autonomous teams adds another layer of complexity. In a comprehensive discussion, Tristan Hamilton, a distinguished member of the HubSpot team, presented a strategic approach to future-proofing Android codebases by leveraging static analysis tools like KtLint and Detekt.

Tristan began by framing the challenges inherent in a codebase that has grown and changed for over eight years. He emphasized that without robust systems, technical debt can accumulate, and architectural principles can erode as different teams introduce their own patterns. The solution, he proposed, lies in integrating automated guardrails directly into the continuous integration (CI) pipeline. This proactive approach ensures a consistent level of code quality and helps prevent the introduction of new technical debt.

He then delved into the specifics of two powerful static analysis tools: KtLint and Detekt. KtLint, as a code linter, focuses on enforcing consistent formatting and style, ensuring that the codebase adheres to a single, readable standard. Detekt, on the other hand, is a more powerful static analysis tool that goes beyond simple style checks. Tristan highlighted its ability to perform advanced analysis, including type resolution, which allows it to enforce architectural patterns and detect complex code smells that a simple linter might miss. He shared practical examples of how Detekt can be used to identify and refactor anti-patterns, such as excessive class size or complex methods, thereby improving the overall health of the codebase.

A significant part of the talk was dedicated to a specific, and crucial, application of these tools: safely enabling R8, the code shrinker and optimizer, in a multi-module Android application. The process is notoriously difficult and can often lead to runtime crashes if not handled correctly. Tristan showcased how custom Detekt rules could be created to enforce specific architectural principles at build time. For instance, a custom rule could ensure that certain classes are not obfuscated or that specific dependencies are correctly handled, effectively creating automated safety nets. This approach allowed the HubSpot team to gain confidence in their R8 configuration and ship with greater speed and reliability.

Tristan concluded by offering a set of key takeaways for developers and teams. He underscored the importance of moving beyond traditional static analysis and embracing tools that can codify architectural patterns. By automating the enforcement of these patterns, teams can ensure the integrity of their codebase, even as it grows and evolves. This strategy not only reduces technical debt but also prepares the codebase for future changes, including the integration of new technologies and methodologies, such as Large Language Model (LLM) generated code. It is a powerful method for building robust, maintainable, and future-ready software.

Links:

PostHeaderIcon [KotlinConf2023] Transforming Farmers’ Lives in Kenya: Apollo Agriculture’s Android Apps with Harun Wangereka

Harun Wangereka, a Software Engineer at Apollo Agriculture and a Google Developer Expert for Android, delivered an inspiring presentation at KotlinConf’23 about how his company is leveraging Android technology to change the lives of farmers in Kenya. His talk detailed Apollo Agriculture’s two core Android applications, built entirely in Kotlin, which are offline-first and utilize server-driven UI (SDUI) with Jetpack Compose to cater to the unique challenges of their user base. Harun is also active in Droidcon Kenya.

Apollo Agriculture’s mission is to empower small-scale farmers by bundling financing, high-quality farm inputs, agronomic advice, insurance, and market access. Their tech-based approach uses satellite data and machine learning for credit decisions and automated operations to maintain low costs and scalability. The customer journey involves signup via agents or SMS/USSD, kyc data collection (including GPS farm outlines), automated credit decisions (often within minutes), input pickup from agro-dealers, digital advice via voice trainings, and loan repayment post-harvest.

Addressing Unique Challenges in the Kenyan Context

Harun highlighted several critical challenges that shaped their app development strategy:
* Low-Memory Devices: Many agents and farmers use entry-level Android devices with limited RAM and storage. The apps need to be lightweight and performant.
* Low/Intermittent Internet Bandwidth: Internet connectivity can be unreliable and expensive. An offline-first approach is crucial, allowing agents to perform tasks without constant internet access and sync data later.
* Diverse User Needs and Rapid Iteration: The agricultural domain requires frequent updates to forms, workflows, and information provided to farmers and agents. A flexible UI system that can be updated without frequent app releases is essential.

These challenges led Apollo Agriculture to adopt a server-driven UI (SDUI) approach. Initially implemented with Anko (a deprecated Kotlin library for Android UI), they later rewrote this system entirely using Jetpack Compose.

Server-Driven UI with Jetpack Compose

The core of their SDUI system relies on JSON responses from the server that define the UI components, their properties, validations, and conditional logic.
Key aspects of their implementation include:
* Task-Based Structure: The app presents tasks to agents (e.g., onboarding a farmer, collecting survey data). Each task is represented by a JSON schema from the server.
* Dynamic Form Rendering: The JSON schema defines various UI elements like text inputs, number inputs, date pickers, location pickers (with map integration for capturing farm boundaries), image inputs (with compression), and more. These are dynamically rendered using Jetpack Compose.
* Stateful Composable Components: Harun detailed their approach to building stateful UI components in Compose. Each question or input field manages its own state (value, errors, visibility) using remember and mutableStateOf. Validation logic (e.g., required fields, min/max length) is also defined in the JSON and applied dynamically.
* Triggers and Conditionals: The JSON schema supports triggers (e.g., “on save”) and complex conditional logic using an internal tool called “Choice Expressions” and an implementation of JSON Schema. This allows UI elements or entire sections to be shown/hidden or enabled/disabled based on user input or other conditions, enabling dynamic and context-aware forms.
* Offline First: Task schemas and user data are stored locally, allowing full offline functionality. Data is synced with the server when connectivity is available.
* Testing: They extensively test their dynamic UI components and state logic in isolation, verifying state changes, validation behavior, and conditional rendering.

Harun shared examples of the JSON structure for defining UI elements, properties (like labels, hints, input types), validators, and conditional expressions. He walked through how a simple text input composable would manage its state, handle user input, and apply validation rules based on the server-provided schema.

Learnings and Future Considerations

The journey involved migrating from Anko to Jetpack Compose for their SDUI renderer, which Compose’s reactive DSL made more manageable and maintainable. They found Compose to be well-suited for building dynamic, stateful UIs.
Challenges encountered included handling keyboard interactions smoothly with scrolling content and managing the complexity of deeply nested conditional UIs.
When asked about open-sourcing their powerful form-rendering engine, Harun mentioned it’s a possibility they are considering, as the core logic is already modularized, and community input could be valuable. He also noted that while some pricing information is dynamic (e.g., based on farm size), they try to standardize core package prices to avoid confusion for farmers.

Harun Wangereka’s talk provided a compelling case study of how Kotlin and Jetpack Compose can be used to build sophisticated, resilient, and impactful Android applications that address real-world challenges in demanding environments.

Links:

PostHeaderIcon [KotlinConf2019] Simplifying Async APIs with Kotlin Coroutines

Tom Hanley, a senior software engineer at Toast, enthralled KotlinConf2019 with a case study on using Kotlin coroutines to tame a complex asynchronous API for an Android card reader. Drawing from his work integrating a third-party USB-connected card reader, Tom shared how coroutines transformed callback-heavy code into clean, sequential logic. His practical insights on error handling, debugging, and testing offered a roadmap for developers grappling with legacy async APIs.

Escaping Callback Hell

Asynchronous APIs often lead to callback hell, where nested callbacks make code unreadable and error-prone. Tom described the challenge of working with a third-party Android SDK for a card reader, which relied on void methods and listener interfaces for data retrieval. A naive implementation to fetch device info involved mutable variables and blocking loops, risking infinite loops and thread-safety issues. Such approaches, common with legacy APIs, complicate maintenance and scalability. Tom emphasized that coroutines offer a lifeline, allowing developers to wrap messy APIs in a clean, non-blocking interface that reads like sequential code, preserving the benefits of asynchrony.

Wrapping the Card Reader API with Coroutines

To streamline the card reader API, Tom developed a Kotlin extension that replaced callback-based interactions with suspend functions. The original API required a controller to send commands and a listener to receive asynchronous responses, such as device info or errors. By introducing a suspend getDeviceInfo function, Tom enabled callers to await results directly. This extension ensured referential transparency, where functions clearly return their results, and allowed callers to control asynchrony—waiting for completion or running tasks concurrently. The approach also enforced sequential execution for dependent operations, critical for the card reader’s connection and transaction workflows.

Communicating with Channels

Effective inter-thread communication was key to the extension’s success. Rather than relying on shared mutable variables, Tom used Kotlin channels to pass events and errors between coroutines. When the listener received device info, it sent the data to a public channel; errors were handled similarly. The controller extension used a select expression to await the first event from either the device info or error channel, throwing errors or returning results as needed. Channels, with their suspending send and receive operations, provided a thread-safe alternative to blocking queues. Despite their experimental status in Kotlin 1.3, Tom found them production-ready, supported by smooth IDE migration paths.

Mastering Exception Handling

Exception handling in coroutines requires careful design, as Tom learned through structured concurrency introduced in Kotlin 1.3. This feature enforces a parent-child relationship, where canceling a parent coroutine cancels its children. However, Tom discovered that a child’s failure propagates upward, potentially crashing the app in launch coroutines if uncaught. For async coroutines, exceptions are deferred until await is called, allowing try-catch blocks to handle them. To isolate failures, Tom used supervisorJob to prevent child cancellations from affecting siblings and coroutineScope blocks to group all-or-nothing operations, ensuring robust error recovery for the card reader’s unreliable USB connection.

Debugging and Testing Coroutines

Debugging coroutines posed initial challenges, but Tom leveraged powerful tools to simplify the process. Enabling debug mode via system properties assigns unique names to coroutines, appending them to thread names and enhancing stack traces with creation details. The debug agent, a JVM tool released post-project, tracks live coroutines and dumps their state, aiding deadlock diagnosis. For testing, Tom wrapped suspend functions in runBlocking blocks, enabling straightforward unit tests. He advised using launch and async only when concurrency is needed, marking functions as suspend to simplify testing by allowing callers to control execution context.

Moving Beyond Exceptions with Sealed Classes

Reflecting on exception handling’s complexity, Tom shifted to sealed classes for error handling. Initially, errors from the card reader were wrapped in exceptions, but frequent USB failures made catching them cumbersome. Exceptions also obscured control flow and hindered functional purity. Inspired by arguments likening exceptions to goto statements, Tom adopted domain-specific sealed classes (e.g., Success, Failure, Timeout) for each controller command’s result. This approach enforced explicit error handling via when statements, improved readability, and allowed result types to evolve independently, aligning with the card reader’s diverse error scenarios.

Links:

PostHeaderIcon [DevoxxBE2013] Architecting Android Applications with Dagger

Jake Wharton, an Android engineering luminary at Square, champions Dagger, a compile-time dependency injector revolutionizing Java and Android modularity. Creator of Retrofit and Butter Knife, Jake elucidates Dagger’s divergence from reflection-heavy alternatives like Guice, emphasizing its speed and testability. His session overviews injection principles, Android-specific scoping, and advanced utilities like Lazy and Assisted Injection, arming developers with patterns for clean, verifiable code.

Dagger, Jake stresses, decouples class behaviors from dependencies, fostering reusable, injectable components. Through live examples, he builds a Twitter client, showcasing modules for API wrappers and HTTP clients, ensuring seamless integration.

Dependency Injection Fundamentals

Jake defines injection as externalizing object wiring, promoting loose coupling. He contrasts manual factories with Dagger’s annotation-driven graphs, where @Inject fields auto-resolve dependencies.

This pattern, Jake demonstrates, simplifies testing—mock modules swap implementations effortlessly, isolating units.

Dagger in Android Contexts

Android’s lifecycle demands scoping, Jake explains: @Singleton for app-wide instances, activity-bound for UI components. He constructs an app graph, injecting Twitter services into activities.

Fragments and services, he notes, inherit parent scopes, minimizing boilerplate while preserving encapsulation.

Advanced Features and Utilities

Dagger’s extras shine: @Lazy defers creation, @Assisted blends factories with injection for parameterized objects. Jake demos provider methods in modules, binding interfaces dynamically.

JSR-330 compliance, augmented by @Module, ensures portability, though Jake clarifies Dagger’s compile-time limits preclude Guice’s AOP dynamism.

Testing and Production Tips

Unit tests leverage Mockito for mocks, Jake illustrates, verifying injections without runtime costs. Production graphs, he advises, tier via subcomponents, optimizing memory.

Dagger’s reflection-free speed, Jake concludes, suits resource-constrained Android, with Square’s hiring call underscoring real-world impact.

Links:

PostHeaderIcon Conférence Devoxx: Introduction aux Google Glass

640px-Image_GoogleGlass

J’ai eu la chance d’assister à l’édition 2014 de Devoxx FR.
La première conférence que j’ai suivie était “Introduction aux Google Glass”, par Alain Régnier (@AltoLabs, +AlainRegnier), dont voici un résumé:

Alain fait partie d’un programme, les Google Glass Explorers, c’est-à-dire les heureux élus qui ont pu se procurer des paires de lunettes Google Glass. Théoriquement, seuls les résidents nord-américains peuvent souscrire au programme ; néanmoins, l’estimation du nombre de Google Glass circulant en France oscille entre 30 et 50 paires.

A mi-chemin entre des lunettes Star Trek et des scouters de Dragon Ball, les Google Glass ressemblent à des lunettes classiques dont l’une des branche est plus épaisse et dont un verre est surmonté d’un prisme et d’une mini-webcam. Le petit bijou de technologie embarque, sous le capot, de nombreux capteurs et connecteurs: visuel, sonore, bluetooth, wifi, et même infrarouge.

Les Google Glass affichent par défaut des informations de quatre types: texte, image, vidéo et une version limitée d’HTML. Elles sont contrôlables de plusieurs façons: à la voix (en lançant le mot magique “OK Glass!”), via un trackpad, une application “web” MyGlassWeb ou enfin une appli Android MyGlassMobile.
En tant qu’outil de développement, un Android Screen Monitor (un simple client ADB) permet d’afficher sur l’écran du PC ce qui est visible par la personne portant les Google Glass: en d’autres termes, le flux de la webcam sur lequel est superposé l’affichage du prisme.
Concernant le développement proprement dit, trois méthodes sont disponibles:

  • Mirror API: les Glass communiquent avec un serveur hébergé par Google, qui redirige vers un serveur concret
  • GDK: il s’agit d’un kit de développement similaire à celui d’Android
  • WearScript: c’est une librairie, non-officielle, permettant de programmer les Glass en JavaScript

Alain a réalisé une démonstration d’utilisation des Glass. Avouons-le: c’est bluffant… En tant que développeur, les perspectives ouvertes par un tel objet connecté sont très enthousiasmantes! Le plus dur va encore être d’attendre que les Glass soient officiellement disponibles dans nos contrées européennes…

PostHeaderIcon [DevoxxFR2013] NFC: Facilitating Mobile Interactions with the Environment

Lecturer

Romain Menetrier is a developer passionate about internet and mobile platforms. He co-organizes the Paris Android User Group and founded Macala for mobile solutions. Previously CTO at Connecthings, a European NFC leader, he now serves as NFC solutions architect at Orange.

Abstract

Romain Menetrier’s talk introduces Near Field Communication (NFC), tracing its RFID and smart card roots while focusing on mobile implementations, especially Android. He demonstrates practical uses like payments and data exchange, explaining standards, tag types, and Android APIs. Through live examples, he highlights NFC’s security via proximity and contextual potential, advocating its adoption for simplified interactions.

Origins and Fundamentals: From RFID to NFC Standards

Menetrier traces NFC to RFID and contactless cards, operating via magnetic field modulation at under 10cm for security—requiring physical presence. An antenna induces power in passive tags, enabling data return without batteries.

Standards: ISO 14443 (cards), 15693 (tags), with modes like reader/writer (phone reads/writes tags), peer-to-peer (device-to-device), and card emulation (phone as card). Frequencies at 13.56MHz allow small antennas in phones.

Tag types vary: Type 1-4 differ in capacity (48B to 32KB), speed, and protocols. NDEF (NFC Data Exchange Format) standardizes data as records with type, ID, payload—e.g., URLs, text, MIME.

Android drives diffusion: since Gingerbread, APIs handle intents on tag discovery, enabling apps to read/write without foreground requirements via tech-lists.

Practical Implementations: Android Apps for Tag Interaction and Peer-to-Peer

Menetrier demos Android apps: reading tags dispatches intents; apps filter via manifests for specific techs (e.g., NfcA). Reading parses NDEF messages into records, extracting payloads like URLs for browser launch.

Writing: create NDEF records (e.g., URI), form messages, write via NfcAdapter. Locking tags prevents overwrites.

Peer-to-peer uses Android Beam (SNEP protocol): share data by touching devices. Implement via CreateNdefMessageCallback for message creation, OnNdefPushCompleteCallback for confirmation.

Code snippet:

NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
adapter.setNdefPushMessageCallback(new CreateNdefMessageCallback() {
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        return new NdefMessage(new NdefRecord[]{createUriRecord("http://example.com")});
    }
}, this);

This enables URL sharing.

Security: short range thwarts remote attacks; presence confirms intent. Contexts from tag locations enhance applications, like venue-specific info.

Everyday Applications and Future Prospects: Payments, Access, and Tracking

Common uses: payments (e.g., Cityzi in France, emulating cards via SIM-secured elements), transport (Navigo integration), access control (badges). Tags in ads track interactions, gauging interest beyond views.

Enterprise: unified NFC cards for canteen, entry—multiple IDs on one chip. Phones emulate cards, even off (via SIM linkage), blockable remotely.

Challenges: ecosystem fragmentation (operators control SIM), but growing adoption. Menetrier sees NFC simplifying interactions, with Android pivotal.

In summary, NFC’s proximity fosters secure, contextual mobile-environment links, poised for widespread use.

Relevant Links and Hashtags

Links:

PostHeaderIcon [DevoxxFR2012] Android Lifecycle Mastery: Advanced Techniques for Services, Providers, and Optimization

Lecturer

Mathias Seguy founded Android2EE, specializing in Android training, expertise, and consulting. Holding a PhD in Fundamental Mathematics and an engineering degree from ENSEEIHT, he transitioned from critical J2EE projects—serving as technical expert, manager, project leader, and technical director—to focus on Android. Mathias authored multiple books on Android development, available via Android2ee.com, and contributes articles to Developpez.com.

Abstract

This article explores Mathias Seguy’s in-depth coverage of Android’s advanced components, focusing on service modes, content provider implementations, and optimization strategies. It examines unbound/bound services, URI-based data operations, and tools like Hierarchy Viewer for performance tuning. Within Android’s multitasking framework, the analysis reviews methodologies for lifecycle alignment, asynchronous execution, and resource handling. Through practical code and debugging insights, it evaluates impacts on battery efficiency, data security, and UI responsiveness. This segment underscores patterns for robust architectures, aiding developers in crafting seamless, power-efficient mobile experiences.

Differentiating Service Modes and Lifecycle Integration

Services bifurcate into unbound (autonomous post-start) and bound (interactive via binding). Mathias illustrates unbound for ongoing tasks like music playback:

startService(new Intent(this, MyService.class));

Bound for client-service dialogue:

private ServiceConnection connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName name, IBinder service) {
        myService = ((MyBinder) service).getService();
    }
    public void onServiceDisconnected(ComponentName name) {
        myService = null;
    }
};
bindService(new Intent(this, MyBoundService.class), connection, BIND_AUTO_CREATE);

Lifecycle syncing uses flags: isRunning/isPaused toggle with onStartCommand()/onDestroy(), ensuring tasks halt on service termination, averting leaks.

Constructing Efficient Content Providers

Providers facilitate inter-app data exchange via URIs. Define via extension, with UriMatcher for parsing:

private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
    matcher.addURI(AUTHORITY, TABLE, COLLECTION);
    matcher.addURI(AUTHORITY, TABLE + "/#", ITEM);
}

Implement insert():

@Override
public Uri insert(Uri uri, ContentValues values) {
    long rowId = db.insert(DBHelper.MY_TABLE, null, values);
    if (rowId > 0) {
        Uri result = ContentUris.withAppendedId(CONTENT_URI, rowId);
        getContext().getContentResolver().notifyChange(result, null);
        return result;
    }
    throw new SQLException("Failed to insert row into " + uri);
}

Manifest exposure with authorities/permissions secures access.

Asynchronous Enhancements and Resource Strategies

AsyncTasks/Handlers offload UI: Extend for doInBackground(), ensuring UI updates in onPostExecute().

Resource qualifiers adapt to locales/densities: values-fr/strings.xml for French.

Databases: SQLiteOpenHelper with onCreate() for schema.

Debugging and Performance Tools

Hierarchy Viewer inspects UI hierarchies, identifying overdraws. DDMS monitors threads, heaps; LogCat filters logs.

Permissions: Declare in manifest for features like internet.

Architectural Patterns for Resilience

Retain threads across rotations; synchronize for integrity.

Implications: These techniques optimize for constraints, enhancing longevity and usability in diverse hardware landscapes.

Mathias’s guidance refines development, promoting sustainable mobile solutions.

Links: