<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ademir Queiroga on Medium]]></title>
        <description><![CDATA[Stories by Ademir Queiroga on Medium]]></description>
        <link>https://medium.com/@admqueiroga?source=rss-7bebee1b1c17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xc2QwFHcpuH_QzF04DHwPA.png</url>
            <title>Stories by Ademir Queiroga on Medium</title>
            <link>https://medium.com/@admqueiroga?source=rss-7bebee1b1c17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:04:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@admqueiroga/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Lint Be Gone: Speed Up Your Android Release APK Builds]]></title>
            <link>https://proandroiddev.com/lint-be-gone-speed-up-your-android-release-apk-builds-aafb7cf430a7?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/aafb7cf430a7</guid>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[build-automation]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 02:02:06 GMT</pubDate>
            <atom:updated>2025-04-18T20:34:44.144Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhance Your CI Efficiency by Disabling Unnecessary Lint Tasks When Building APKs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZMnD49RTcA_pOJHg" /><figcaption>Photo by <a href="https://unsplash.com/@miracleday?utm_source=medium&amp;utm_medium=referral">Elena Mozhvilo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I&#39;ve been exploring ways to speed up a white-label automated app-building system. After a deeper inspection, I realized that the Android Gradle build task could run much faster for assemble tasks, a.k.a. building APKs. Given the number of apps this system generates, even minor improvements can be highly valuable.</p><p>These days, when you upload an Android app to Google Play or the Amazon Appstore, an Android App Bundle (AAB) is required<strong>*</strong>. When building AABs, the lint task doesn&#39;t run by default. If your only requirement is an AAB, this article won&#39;t be your recipe for speed. However, if you still need to generate APKs, whether for uploading to an automated test platform, easier distribution to QA teams, or other specific needs, keep reading.</p><p><strong>*Note</strong>: Amazon Appstore still accepts APKs.</p><h4>Gradle Build</h4><p>The Gradle build system provides many optimizations for completing tasks faster. It caches the inputs and outputs of the executed tasks, and if the inputs haven&#39;t changed, it skips the task and reuses the cached output. It is also capable of running independent tasks in parallel. You can learn more about Gradle caching <a href="https://docs.gradle.org/current/userguide/build_cache.html">here</a> and parallel task execution <a href="https://docs.gradle.org/current/userguide/performance.html#parallel_execution">here</a>.</p><p>However, our white-label system executes tasks in a fresh and clean workspace, similar to ephemeral CI environments, which prevents us from leveraging caching out of the box. Therefore, I aimed to prevent unnecessary tasks from running.</p><p>I ran a clean release build with Gradle&#39;s --scan option and began exploring the Timeline. As its name suggests, the Timeline displays each executed task chronologically, showing how long it took to start and finish. After I ordered the tasks by duration, I noticed that lintVitalAnalyzeRelease, a task that runs by default for a release APK build consumed a significant portion of the overall execution time. This appeared to be a low-hanging fruit I could easily tackle.</p><blockquote>For demonstration purposes, I used the <strong>mozilla-mobile/fenix</strong> project to showcase the Gradle build scan results but the same idea applies to any Android project.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwxE1fmK2CtZpEkVB3Uc6A.png" /><figcaption>Gradle Scan Timeline from mozilla-mobile/fenix Project.</figcaption></figure><p>The lint task for the app module alone took <strong>33.944</strong> seconds to complete, accounting for approximately <strong>15%</strong> of the entire execution time. It&#39;s important to note that the lint task runs for all Android modules the project depends on. Below, you&#39;ll find the Gradle Scan Timeline for android/nowinandroid, a project with 21 Android module dependencies for the assembleRelease task at the time of writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sJVRPXLPNJj80qr3KRAcg.png" /><figcaption>Gradle Scan Timeline filtered by lint tasks from android/nowinandroid project.</figcaption></figure><p>By filtering for tasks of type AndroidLintAnalysisTask, you can see how much time each module&#39;s code analysis took. To be fair, some of these tasks ran in parallel, so the report’s <strong>5m 11s</strong> duration doesn’t reflect the actual time, as the overall execution finished in <strong>4m 16s</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ktkw09LeuY7gxBvM_NB1Qg.png" /><figcaption>Overall task execution duration for the android/nowinandroid project.</figcaption></figure><h4>Lint. The good, the bad, and the lintVitalRelease task</h4><p>A linter is a tool that analyzes your code to identify syntax errors, potential bugs, vulnerabilities, and code smells, among other issues. In an Android project, the Android Gradle Plugin provides numerous lint rules that address a wide range of concerns, including accessibility, performance, usability, and security. If you&#39;re up for a challenge, you can also create custom lint checks for your specific needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VL3jVbVgEZixWqGlUHVxQ.png" /><figcaption>Out-of-the-box AGP lint rules</figcaption></figure><p>The cost of these checks increases somewhat linearly with the size of your project, as larger codebases have more lines of code to be validated against lint rules. It&#39;s important to note that lint tasks, by default, are only executed for release APK builds. This means they won&#39;t run each time you deploy changes to a device during development or when you build an app bundle.</p><p>Below is an overview of the impact of lint tasks in the assembleRelease task on projects of varying sizes. All tasks were executed on an M3 Pro Mac.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/166d6ea43d6534836f67bfaa098d02a6/href">https://medium.com/media/166d6ea43d6534836f67bfaa098d02a6/href</a></iframe><blockquote>Note: The LOC&#39;s (Lines of Code) accounts for Java, Kotlin and XML files only.</blockquote><h4>Disabling Lint in CI builds</h4><p>Logs from successful builds, including lint task reports, are frequently overlooked in CI environments. This oversight means valuable processing time, and the money it represents can be wasted.</p><p>If you&#39;re not actively using these lint reports and run multiple builds regularly, you can save time and money by disabling the execution of lint tasks. Add the following lines to your project&#39;s Gradle configuration file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed4dac62c9b5e280713371910cfce9a/href">https://medium.com/media/7ed4dac62c9b5e280713371910cfce9a/href</a></iframe><p>You might not want lint tasks to be permanently disabled. Instead, you can control their execution by passing an extra parameter to Gradle tasks. For example, you can run ./gradlew assembleRelease -PdisableReleaseLint to disable lint only when this parameter is present. Here&#39;s how to set it up in your Gradle configuration file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76634812dcf5e92c2d29d1c5032cdc9b/href">https://medium.com/media/76634812dcf5e92c2d29d1c5032cdc9b/href</a></iframe><p>These samples use the AGP Lint DSL. You can learn more about it in the <a href="https://developer.android.com/reference/tools/gradle-api/8.6/com/android/build/api/dsl/Lint">official docs</a>.</p><h4>Wrapping up!</h4><p>Optimizing CI build times by managing Android Gradle tasks is not just about increasing speed and saving costs, it&#39;s also about freeing up developer time for more critical tasks. Disabling the lint task was a low-hanging fruit that brought immediate benefits. While the advantages of this approach might seem minimal for smaller projects, dealing with hundreds or thousands of builds for each new app version can significantly reduce computing load. More importantly, it accelerates delivery, ensuring the latest version quickly get into users hands.</p><p>For teams managing extensive build pipelines, these insights can serve as a foundation for exploring additional CI/CD process optimizations.</p><h4>Thank you!</h4><p>Please share your numbers if you&#39;ve made it here and this post has helped you! I&#39;m keen to see the lint impact in different projects.</p><p>Do you have any other tips on how to improve build time? I would love to discuss!</p><p>Feel free to connect with me on <a href="https://linkedin.com/in/ademirqueiroga">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aafb7cf430a7" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/lint-be-gone-speed-up-your-android-release-apk-builds-aafb7cf430a7">Lint Be Gone: Speed Up Your Android Release APK Builds</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Android TV Playback Experience with MediaSession]]></title>
            <link>https://proandroiddev.com/enhancing-android-tv-playback-experience-with-mediasession-f1554ceae2f1?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1554ceae2f1</guid>
            <category><![CDATA[android-tv]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 10:53:40 GMT</pubDate>
            <atom:updated>2023-03-19T04:50:50.632Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enabling playback voice control using Google Assistant, Alexa, and any other integrated voice assistant</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Gu-zOhUNEA6kVxY" /><figcaption>Photo by <a href="https://unsplash.com/@romewilkersonphotography?utm_source=medium&amp;utm_medium=referral">Rome Wilkerson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we&#39;ll learn about Android MediaSession API, why we should use it, and how to implement it on Android TV (or Fire TV) apps. After setting the ground, we&#39;ll follow a step-by-step guide on a basic MediaSession implementation. The sample app used for this article and all the code below can be found <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/MediaSession">here</a>.</p><p>If you need to become more familiar with or need a recap on how playback controls are implemented using the Leanback components, check my previous articles. I cover from the basics to further customizations on the Leanback playback controls.</p><p><a href="https://proandroiddev.com/android-tv-leanback-playback-controls-part-1-cfbb938a2b89">📺 Android TV Leanback: Playback Controls — Part 1</a></p><h3>What is a MediaSession?</h3><p>As per the documentation, a MediaSession &quot;<em>Allows interaction with media controllers, volume keys, media buttons, and transport controls</em>&quot;. More than that, a MediaSession is the control center where we can read information about what is currently being played on the Android device and dispatch media control actions such as <strong>play</strong>, <strong>pause, rewind, skip, seek, and more</strong>.</p><p>From an <strong>active </strong>MediaSession, the Android system can control an app&#39;s media playback and query information about it. Whenever you send, for example, a <strong>play/pause </strong>command by pressing or tapping on your earbuds, you are triggering MediaSession callbacks that ask the underlying player app to perform those actions.</p><p>On the other hand, a music or video app should provide information about what&#39;s currently playing to an <strong>active </strong>MediaSession. This is how the Android system can display this data to the user and provide interfaces where the user can dispatch media actions—for example, using on-screen buttons or sending voice commands through Google Assistant or Amazon Alexa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*GxqQTOhiIyz7xRnyhMNQFQ.png" /><figcaption>Spotify MediaSession notification</figcaption></figure><h3>What are the benefits?</h3><p>The benefits of implementing the MediaSession in our apps vary from device to device.</p><ul><li>The <strong>media playback can be controlled by voice</strong> on devices that support Google Assistant or other kinds of voice assistant<strong>.</strong></li><li>On TV devices that support HDMI-CEC, the playback can be controlled <strong>using the conventional remote control media keys</strong>.</li><li>On phones, on-screen media controls. Depending on the Android version, the OS can get information about a MediaSession and <strong>provide media controls </strong>that<strong> </strong>will appear <strong>on the lock screen</strong>.</li><li>It also enables other devices, for example, <strong>wearables,</strong> to connect to your app&#39;s media session and <strong>control it from your wrist</strong>.</li><li>Provide a way for other apps to control your MediaSession. For example, a navigation <strong>app can request a music player to play your favorite playlist</strong> when you start driving.</li></ul><p>This is a powerful API. It&#39;s<strong> not just about transport controls</strong> (play, pause, etc.) <strong>or displaying the content metadata. </strong>It&#39;s also about sending specific media playback requests to an app capable of handling and performing them. This is what allows you to say confidently:</p><blockquote>&quot;Hey Google, play The <strong>Suburbs</strong> from Arcade Fire on Spotify.&quot;</blockquote><h3>Step-by-Step Implementation Guide</h3><h4>Setting up the project</h4><p>The first step is to add the androidx.media dependency on your app build.gradle.</p><pre>implementation &quot;androidx.media:media:1.6.0&quot;</pre><p>After that, and only if you plan to target Amazon Fire TV devices, you must add the following permission and, optionally, a meta-data to the AndroidManifest.xml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4823ca31104d4391e5ebcc4345fe6177/href">https://medium.com/media/4823ca31104d4391e5ebcc4345fe6177/href</a></iframe><p><strong>Note: </strong>The com.amazon.voice.supports_background_media_session metadata is optional, and the behavior change from its usage is described <a href="https://developer.amazon.com/docs/fire-tv/mediasession-api-integration.html#enhanced-experience-for-voice-enabled-playback-controls-using-media-session-optional">here</a>.</p><h4>Creating the MediaSession</h4><p>To create a MediaSession, the only required arguments are a Context, and a String tag used to identify the MediaSession when debugging.</p><pre>private val mediaSession = MediaSessionCompat(context, &quot;VideoPlayback&quot;)</pre><p>Conceptually, a MediaSession should live as long as the media player lives. On video apps, this usually means as long as the Activity or Fragment with the playback UI is in the foreground. Meanwhile, an audio app MediaSession might have the same lifecycle of the Service that holds the player instance, as they usually support background playback.</p><p>With this in mind, I decided to manage the MediaSession lifecycle for the sample app completely inside the SimplePlaybackTransportControlGlue as it receives all the callbacks about the host lifecycle, in this case, a VideoSupportFragment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad62578dd86ff74a3a5fe1ee373f7bf4/href">https://medium.com/media/ad62578dd86ff74a3a5fe1ee373f7bf4/href</a></iframe><p>Then, we start the MediaSession configuration by providing a listener that will be called whenever media actions are dispatched. We do so by calling the MediaSession.setCallback() function and passing an instance of MediaSessionComapt.Callback. Inside these callbacks, we&#39;ll perform the play, pause, seek, and any other operation supported by our MediaSession.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e41bafe9a707aaec5f6b340de5e80178/href">https://medium.com/media/e41bafe9a707aaec5f6b340de5e80178/href</a></iframe><p>For the callbacks to be called, though, the MediaSession <strong>must be active</strong>. We can activate and deactivate a MediaSession by calling MediaSession.isActive = true/false.</p><h4>Playback State</h4><p>Once you have the playback information about your media, you should pass it on to the MediaSession. For that, we use the PlaybackState class. This is how the MediaSession knows which actions are available and the current playback state.</p><p>The existing playback states for a MediaSession, and their documentation can be found inside the PlaybackStateCompat class or <a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/oreo-dr3-release/media-compat/java/android/support/v4/media/session/PlaybackStateCompat.java#229">here</a>. In short, they are: STATE_NONE, STATE_STOPPED, STATE_PAUSED, STATE_PLAYING, STATE_FAST_FORWARDING, STATE_REWINDING, STATE_BUFFERING, STATE_ERROR, STATE_CONNECTING, STATE_SKIPPING_TO_PREVIOUS, STATE_SKIPPING_TO_NEXT, and STATE_KIPPING_TO_QUEUE_ITEM.</p><p>We can store an Int value that represents the current playback state, and whenever it changes, we will update the MediaSession PlaybackState.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f4bbdfac767cfb11d3a77a287d247da/href">https://medium.com/media/2f4bbdfac767cfb11d3a77a287d247da/href</a></iframe><p>Still, inside the SimplePlaybackTransportControlGlue, we can listen to almost all player events we need. This was another reason I decided to let the MediaSession inside the glue.</p><p>Add the following code to your glue to listen to these events and update the playbackState value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/062b7b8dd0f61eb023380f23c9111332/href">https://medium.com/media/062b7b8dd0f61eb023380f23c9111332/href</a></iframe><p>A few events aren&#39;t available to the glue directly. More specifically, the buffering started/finished, and error events are sent to the glue host, the VideoPlaybackFragment. You can receive them on the host and forward them to the glue using public functions. (For simplicity, I decided not to add the error event as there are <a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/oreo-dr3-release/media-compat/java/android/support/v4/media/session/PlaybackStateCompat.java#391">too many of them</a>)</p><h4>Playback Actions</h4><p>We must pass to the MediaSession the actions that it supports. This information is passed as a <strong>bitmask of the available actions</strong>. At the time of writing, there are 22 different actions a MediaSession supports (<a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/oreo-dr3-release/media-compat/java/android/support/v4/media/session/PlaybackStateCompat.java#71">check them here</a>). Again, we&#39;ll only support the most common media actions for simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e0dc8227855a8b07da0fea83c0a8f1/href">https://medium.com/media/45e0dc8227855a8b07da0fea83c0a8f1/href</a></iframe><p><strong>Note: </strong>The supported actions should be updated based on your media playback. For example, if your app plays ads, usually, you shouldn&#39;t allow the user to fast-forward or rewind when the ad is playing. In this case, you should update the PlaybackState and remove the ACTION_FAST_FORWARD, ACTION_REWIND, and any other action that should be prevented during ad playback. Look at the mediaSessionSupportedActions() from the sample app <a href="https://github.com/ademirqueiroga/leanback-samples/blob/9f0cf1f9147339af2e952d827d2421b6a7adac07/MediaSession/app/src/main/java/me/admqueiroga/mediasession/playback/SimplePlaybackTransportControlGlue.kt#L140">here</a> to clarify this idea.</p><h4>Setting MediaSession PlaybackState</h4><p>After gathering all the information about the current playback status, you can pass it to the MediaSession like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c3b825f106c6537974e092e827cb9e2/href">https://medium.com/media/0c3b825f106c6537974e092e827cb9e2/href</a></iframe><p><strong>Note: </strong>This is where you can also set the error state of the MediaSession by calling PlaybackStateCompat.Builder.setErrorMessage().</p><h4>Releasing the MediaSession</h4><p>After finishing the playback, remember to call MediaSession.release() to release the resources used by the MediaSession that won&#39;t be needed anymore.</p><h3>Testing the Implementation</h3><p>Suppose you are using an emulator or cannot use the voice assistant on your device for any specific reason. In that case, you can use the adb to dispatch the MediaSession actions directly to your device.</p><ul><li>On <strong>Android 11</strong> and above, you can run adb shell cmd media_session dispatch &lt;play|pause|play-pause|rewind|fast-forward|next|previous|stop|mute&gt;.</li><li>On <strong>lower versions, </strong>the command is slightly different. adb shell media dispatch &lt;play|pause|play-pause|rewind|fast-forward|next|previous|stop|mute&gt;.</li></ul><h3>ExoPlayer Integration</h3><p>ExoPlayer has an extension called MediaSessionConnector that facilitates the integration with the MediaSession API. You can check <a href="https://codelabs.developers.google.com/codelabs/supporting-mediasession#0">this Google codelab</a>, the <a href="https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ext/mediasession/MediaSessionConnector.html">official docs</a>, and <a href="https://medium.com/google-exoplayer/the-mediasession-extension-for-exoplayer-82b9619deb2d">this medium post</a> for more details.</p><h3>Reference and Documentation</h3><ul><li><a href="https://developer.android.com/reference/kotlin/android/support/v4/media/session/MediaSessionCompat">MediaSessionCompat documentation</a></li><li><a href="https://developer.android.com/training/tv/playback/media-session">Implement a MediaSession official training</a></li><li><a href="https://codelabs.developers.google.com/codelabs/supporting-mediasession#0">MediaSession with ExoPlayer codelab</a></li><li><a href="https://developer.android.com/guide/topics/media-apps/media-apps-overview">Media App architecture overview</a></li></ul><h3>Thank you!</h3><p>Thanks for going through this entire post! Make sure to check the <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/MediaSession">sample app</a> and follow me to be notified when new content is available!</p><p>I suggest this very special list of Android TV articles. It is frequently updated, and there&#39;s a lot of value in there!</p><p><a href="https://admqueiroga.medium.com/list/9a363e566f38">📺 Android TV Leanback Guide</a></p><p>You can also connect with me on <a href="https://twitter.com/@admqueiroga">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1554ceae2f1" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/enhancing-android-tv-playback-experience-with-mediasession-f1554ceae2f1">Enhancing Android TV Playback Experience with MediaSession</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Android TV Leanback: HeadersSupportFragment]]></title>
            <link>https://proandroiddev.com/android-tv-leanback-headerssupportfragment-a-detailed-guide-15afc02732cb?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/15afc02732cb</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-leanback]]></category>
            <category><![CDATA[android-tv]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 02:24:05 GMT</pubDate>
            <atom:updated>2023-03-23T04:46:22.800Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn the ins and outs of your user&#39;s welcome screen to create a more engaging and personalized experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JYZo51BYPkoKctNS" /><figcaption>Photo by <a href="https://unsplash.com/@nabiloh?utm_source=medium&amp;utm_medium=referral">Nabil Saleh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Understanding the internals of the Leanback APIs is sometimes quite tricky, but it&#39;s something we, as developers, must do to make sure we&#39;re able to create apps that look and behave correctly to our users. In this post, we&#39;ll dive deep into the HeadersSupportFragment, which is part of the BrowseSupportFragment, and almost always, the first piece of content users see in an Android TV app. We will learn about its creation, how it behaves, and how we can customize it.</p><h3>The Beginning</h3><p>As stated in the introduction, the HeadersSupportFragment is part of the BrowseSupportFragment. The BrowseSupportFragment is often the first screen that a user sees when opening an Android TV app, and it&#39;s where the user can browse and discover content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UkYNsF6wc0xoaSTezJxyg.png" /><figcaption>BrowseSupportFragment with visible headers</figcaption></figure><h4>HeadersSupportFragment creation and configuration</h4><p>The BrowseSupportFragment has a function called onCreateHeadersSupportFragment() which is responsible for returning an instance of HeadersSupportFragment to be used inside it. It is a public function, so it is possible to override it if you want to provide a custom implementation of your own HeadersSupportFragment.</p><pre>public HeadersSupportFragment onCreateHeadersSupportFragment() {<br>    return new HeadersSupportFragment();<br>}</pre><p>After that, still inside the BrowseSupportFragment.onCreateView() the HeadersSupportFragment is added to its container by a FragmentTransaction performed by the BrowseSupportFragment. Then, the following steps happen:</p><ul><li>Update HeadersSupportFragment visibility based on the state passed to BrowseSupportFragment.setHeaderState(state). The available states are:</li></ul><pre>/** The headers fragment is enabled and shown by default. */<br>public static final int HEADERS_ENABLED = 1;<br>/** The headers fragment is enabled and hidden by default. */<br>public static final int HEADERS_HIDDEN = 2;<br>/** The headers fragment is disabled and will never be shown. */<br>public static final int HEADERS_DISABLED = 3;</pre><ul><li>Calls HeadersSupportFragment.setPresenterSelector() passing the PresenterSelector provided to BrowseSupportFragment.setHeaderPresenterSelector(). This PresenterSelector should support at least three types of items. Which are, DividerRow, SectionRow, and Row.</li></ul><p><strong>Note</strong>: The HeadersSupportFragment already have out-of-the-box implementations for these Row types, but we can provide custom implementations. As a HeaderSupportFragment is a subclass of BaseRowSupportFragmeent, customizing its rows, it&#39;s just a matter of having a custom Presenter for its items.</p><ul><li>The HeadersSupportFragment has its adapter, OnHeaderViewSelectedListener and OnHeaderClickedListener set. The adapter is responsible for providing the items. The default implementation for its OnHeaderViewSelectedLister changes or selects the content of the BrowseSupportFrament. As for the OnHeaderClickedListener, its default implementation hides the HeaderSupportFragment when an item is clicked.</li><li>The background color of the HeadersSupportFragment is set using the color provided to the BrowseSupportFragment.setBrandColor(). For example:</li></ul><pre>override fun onCreateHeadersSupportFragment(): HeadersSupportFragment {<br>    // This can also be done on the onViewCreated()<br>    brandColor = Color.RED<br>    return super.onCreateHeadersSupportFragment()<br>}</pre><ul><li>At this point, the BrowseSupportFragment.onViewCreated() finished and the BrowseSupportFragment.onStart() will be called. Inside the onStart() the alignment of the HeadersSupportFragment will be set based on a Leanback theme property called browseRowsMarginTop. This property, as its name suggests, is also used by the BrowseSupportFragment to set the top margin of its first row.</li><li>If you want to change the HeadersSupportFragment items alignment, you need to do so after the call to super.onCreate()</li></ul><pre>override fun onStart() {<br>    super.onStart()<br>    headersSupportFragment.setAlignment(400)<br>}</pre><p><strong>Note: </strong>The idea of bothHeadersSupportFragment and BrowseSupportFragment using the same value from browseRowsMarginTop to set their top margin helps them to better align the selected row on the header with the selected row on the BrowseSupportFragment when the BrowseSupportFragment is used to display only ListRows. If the BrowseSupportFragment is displaying a PageRow this alignment doesn&#39;t matter as the PageRow content will fill the entire fragment.</p><p>We&#39;ll cover PageRows and the details of the BrowseSupportFragmenton another post. Make sure to follow me to be notified when it&#39;s released!</p><h3>In a Nutshell</h3><ul><li>You can enable or disable the headers of a BrowseSupportFragment by setting calling BrowseSupportFragment.setHeaderState(state) and passing the desired state.</li><li>Change HeadersSupportFragment background-color by calling HeadersSupportFragment.setBrandColor(color).</li><li>Change or provide new types of Presenter to your HeadersSupportFragment.</li><li>Change the OnHeaderViewSelectedListener and OnHeaderClickListener implementations of you HeadersSupportFragment.</li></ul><h3>Customizing HeadersSupportFragment Items</h3><p>As we saw earlier, the HeadersSupportFragment should support three different types of items: DividerRow, SectionRow, and Row. Take a look at how these items are displayed with their default Presenter implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04kRvuBPed_Z5I6v-sSSnA.png" /><figcaption>BrowseSupportFragment with three types of items in HeadersSupportFragment</figcaption></figure><h4>IconSectionRow and IconSectionPresenter</h4><p>To show how we can customize the items of a HeadersSupportFragment, we will create a IconSectionPresenter which will render a SectionRow with an image on the left of its text.</p><p>Let&#39;s start by creating a subclass of SectionRow that holds the id of a drawable to be used on the row.</p><pre>class IconSectionRow(<br>    @DrawableRes val icon: Int,<br>    headerItem: HeaderItem<br>) : SectionRow(headerItem)</pre><p>After that, we need to create a Presenter capable of performing the creation and binding of an IconSectionRow. We&#39;ll do that by extending the RowHeaderPresenter and adding just a few lines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09ae848fe9150e1b3eaa07894a451b8a/href">https://medium.com/media/09ae848fe9150e1b3eaa07894a451b8a/href</a></iframe><p>And here&#39;s the R.layout.icon_section_row.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4789d9d0c92d8a7b8825c34baead0d/href">https://medium.com/media/cf4789d9d0c92d8a7b8825c34baead0d/href</a></iframe><p><strong>Note: </strong>When creating layouts for non-focusable rows, like dividers and sections, disable the focus on its root view. Otherwise, they will be able to receive focus, and sometimes this can lead to a ClassCastException depending on the type of your item and ViewHolderused for it as the HeadersSupportFragment tries to cast the selected items ViewHolders to RowHeaderPresenter.ViewHolder.</p><h4>DividerRow and SpaceDividerPresenter</h4><p>Similar to how we created a custom Presenter for theSectionRow, we&#39;ll create one for the DividerRow. We&#39;ll build a presenter that displays the divider as a space instead of a 1dp line. In this case, we only need a custom presenter, as the item, the DividerRow, does not need to hold any extra information (like the icon from the IconSectionRow).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33dfaa7de48ec3927f2f03ad5c268797/href">https://medium.com/media/33dfaa7de48ec3927f2f03ad5c268797/href</a></iframe><h4>Adding Custom Presenters</h4><p>Last, we must add both newly created presenters to the HeadersSupportFragment presenter selector. Make sure you are doing this only after the call to BrowseSupportFragment.onCreateView() finished, as the HeadersSupportFragment is only instantiated inside it.</p><p>Inside your BrowseSupportFragment, or in your custom implementation of HeadersSupportFragment, do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1d3d435a8a4c6784838119467e5adf/href">https://medium.com/media/7e1d3d435a8a4c6784838119467e5adf/href</a></iframe><h4>Theme Managed Attributes</h4><p>A few attributes from the HeadersSupportFragment are provided by your app theme. When creating a theme for an Android TV app, you should extend from Theme.Leanback. This base theme has all properties the Leanback components use to set sizes, margins, paddings, colors, and more. Below is a list of the attributes that are used by the HeadersSupportFragment.</p><ul><li>lb_browse_headers_width: The width of the HeadersSupportFragment.</li><li>lb_browse_headers_paddding_end: HeadersSupportFragment padding end.</li><li>lb_browse_headers_z: Elevation of the HeadersSupportFragment root view.</li><li>lb_browse_header_fading_length: Fading edge width. The fading edge covers the end of a header text when the text is too long.</li><li>lb_headers_right_fading: Background drawable used by the fading edge.</li><li>headersVerticalGridStyle: Style for the VerticalGridView of the HeadersSupportfragment. The default theme is configured as shown below:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2c1d47560ecdd3fd1df9b3538170ef/href">https://medium.com/media/7d2c1d47560ecdd3fd1df9b3538170ef/href</a></iframe><ul><li>lb_section_header &amp; lb_header: Default layout file for the SectionRow and Row views, respectively.</li></ul><p><strong>Note: </strong>On the <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/CustomHeaders">sample app</a>, none of these theme properties were changed.</p><h3>Final Result!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Iw1un_fMNMcbiHbLHVDkQ.png" /></figure><p>Thanks for reading this post! Make sure to check the <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/CustomHeaders">sample app</a> created especially for this article. Take a look at the <a href="https://developer.android.com/reference/androidx/leanback/app/HeadersSupportFragment">official documentation</a> on HeadersSupportFragment.</p><p>Also, check this list I created with my Android TV Leanback series articles:</p><p><a href="https://admqueiroga.medium.com/list/9a363e566f38">📺 Android TV Leanback Guide</a></p><p>You can also connect with me on <a href="https://twitter.com/@admqueiroga">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15afc02732cb" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-tv-leanback-headerssupportfragment-a-detailed-guide-15afc02732cb">Exploring Android TV Leanback: HeadersSupportFragment</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Android TV Preview Channels: A Beginner's Guide]]></title>
            <link>https://proandroiddev.com/android-tv-preview-channels-a-beginners-guide-52621502e996?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/52621502e996</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[google-tv]]></category>
            <category><![CDATA[android-leanback]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Wed, 22 Feb 2023 23:43:25 GMT</pubDate>
            <atom:updated>2023-02-23T23:17:58.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ijm1HynKZqPG51Cu" /><figcaption>Photo by <a href="https://unsplash.com/@techdailyca?utm_source=medium&amp;utm_medium=referral">Tech Daily</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How nice would it be to display your app content before the user thinks about opening it? Guess what? This is possible with the <strong>Channels API</strong>!</p><p>In this post, we will go through a step-by-step guide with some helpful insights on creating and publishing <strong>your app&#39;s Preview Channels to the Android TV home screen </strong>and how to handle <strong>user interaction with your channels</strong>. Make sure to check out the <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/ChannelSample">sample app</a> with all the concepts of this post.</p><h3>Preview Channels</h3><p>Android TV supports various channels, from ATSC and DVB channels, i.e., cable channels, to other standards of satellite channels. Today we&#39;ll discuss a specific channel type called <strong>Preview Channels.</strong></p><p>You might have already seen a few if you&#39;re familiar with the Android TV home screen. Every time you install an app, and you can discover the app&#39;s content on the home screen, chances are that you&#39;re seeing a <strong>Preview Channel. </strong>Preview Channels can be understood simply as <strong>rows of content</strong> that your app can add to the tv home screen.</p><p>Here&#39;s the opening from the <a href="https://developer.android.com/training/tv/discovery/recommendations-channel">official documentation</a>:</p><blockquote>&quot;The Android TV home screen, or simply the <em>home screen</em>, provides a UI that displays recommended content as a table of <em>channels</em> and <em>programs</em>. Each row is a channel. A channel contains cards for every program available on that channel.&quot;</blockquote><h4>Keep your users engaged!</h4><p>Having relevant and updated content on the home screen is an effective way to keep your users engaged with your app. Sometimes, the only thing apart from the user returning to your app is visual encouragement. That&#39;s why <strong>Preview Channels are so appealing</strong>. On a glance at the home screen, the user is one click away from consuming your app&#39;s content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ih8r4PPsyjgq_1G1fzgNUQ.gif" /><figcaption>Preview channel example</figcaption></figure><blockquote><strong>Note: </strong>Preview Channels are only available in Android TV 8.0 (API 26) and later. If you want to support a similar feature in older versions, look at the <a href="https://developer.android.com/training/tv/discovery/recommendations-row">Recommendations Row documentation</a>.</blockquote><h3>How does it work?</h3><p>Apps can perform all <strong>CRUD</strong> (Create, Read, Update, and Delete) operations in channels using the TvProvider and ContentProvider APIs (we&#39;ll cover those in more detail later). Still, to show the channels on the home screen, the app must ask the user&#39;s permission, except for the first published channel.</p><p>A channel <strong>is not published</strong>, i.e., visible on the home screen as soon as it&#39;s created. For that, we must ask the user permission <strong>to publish the channel</strong>.</p><p><strong>The first channel created by your app can be published without asking for the user&#39;s permission. </strong>We&#39;ll call the first channel the<strong> &quot;default&quot; </strong>channel<strong>. </strong>With this in mind, it is important never to delete your default channel. Otherwise, we&#39;ll need to ask the user permission to publish it again. You should instead repurpose it, changing its information and content, and never delete and recreate it.</p><h4>Programs</h4><p>Channels without content aren&#39;t much. They&#39;re not even displayed on the home screen. To add content to channels, we need to create <strong>Programs. </strong>A program will become a card on a channel row.</p><p><strong>CRUD</strong> operations on programs are done using the same TvProviderand ContentProvider APIs mentioned above. After creating programs, we should add them to a channel to make their content available to the users.</p><p>You can provide a lot of information about your programs, such as <strong>title</strong>, description, <strong>type</strong>, genre, <strong>video preview URL</strong>, <strong>thumbnail</strong>, duration, and the list goes on… Depending on the type of your program (if it&#39;s a movie, a series episode, a season, or any other kind), some pieces of information are more relevant than others. <strong>Keep this in mind when creating your programs to provide the best experience for your users. </strong>You<strong> </strong>can check<strong> </strong>the complete list of program attributes to decide which ones to provide <a href="https://developer.android.com/training/tv/discovery/recommendations-channel#program_attributes">here</a>.</p><p>After creating programs, adding them to channels, and publishing them, they&#39;ll be visible on the home screen, where users can quickly deep-link to your app&#39;s home or straight to a video/content playback.</p><p><strong>💡 ️Tip:</strong> Consider how your content can be structured in this channel/program hierarchy before writing any code<strong>.</strong></p><h3>Enough with theory. Please show me the code!</h3><p>Start by adding the TvProvider dependency to your app&#39;s build.gradle.</p><pre>dependencies {<br>    ...<br>    implementation &#39;androidx.tvprovider:tvprovider:1.1.0-alpha01&#39;<br>}</pre><h3>Creating or Updating a Channel</h3><p>The implementations to create or update a channel are very similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b032e6e3774b5425fa17146802bacfce/href">https://medium.com/media/b032e6e3774b5425fa17146802bacfce/href</a></iframe><blockquote><strong>Note: </strong>We will cover the queryChannels() function later. For now, assume that it returns all channels of your app.</blockquote><p>After building the channel, we need to use the ContentResolver to <strong>insert or update it on the database</strong> which is used by the system to get information about the channels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3093bb6a99ab1d2595894031b42a9e/href">https://medium.com/media/0e3093bb6a99ab1d2595894031b42a9e/href</a></iframe><h4>Publishing a channel</h4><p>As mentioned, creating a channel is not enough to make it visible on the home screen. We need to ask for the user&#39;s permission to publish the channel. The code for this is very straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57438871308cec936fe2fbbb9718f26a/href">https://medium.com/media/57438871308cec936fe2fbbb9718f26a/href</a></iframe><p>This will prompt the user with a dialog asking to add the channel to the TV home screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pniFv3b5ydw8XoPM5AVWrw.png" /></figure><h4>The default channel</h4><p>To create the default channel, we will use a BroadcastReceiver usually triggered once your app is installed. In rare cases, it can be triggered only on the first app launch. Add the following to your AndroidManifest.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd966ef8088c5f7ada244a7f3ac77ba/href">https://medium.com/media/9fd966ef8088c5f7ada244a7f3ac77ba/href</a></iframe><p>And here&#39;s how we can implement the BroadcastReceiver:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38981861f27ac7ad74a3d5ee3e8d5fbe/href">https://medium.com/media/38981861f27ac7ad74a3d5ee3e8d5fbe/href</a></iframe><p>💡 <strong>Tip</strong>: Notice the call to Channel.setInternalProviderId() function. This is a way to set the id your app uses to identify the channel. As the channel id needs to be unique among all the installed apps, it is generated by the database, and we can&#39;t change it. That&#39;s why we have the setInternalProviderId() API to store your app&#39;s internal id for that channel.</p><p>To test your BroadcastReceiver implementation, you can trigger its Intent via adb with the following code:</p><pre>adb shell am broadcast -a android.media.tv.action.INITIALIZE_PROGRAMS -n \<br>    your.package.name/.YourReceiverName</pre><h3>Querying channel information</h3><p>To manage the app channels, we usually need to query for their data to decide what information needs to change, what programs we need to add or remove, and what shouldn&#39;t be touched.</p><p>There are a few ways and APIs to help us with that. If you want complete control and access to all your channel data, use the ContentResolver API and query the channels database for the exact information you need. If you only need to read the basics about your channel, you can use the PreviewChannelHelper API.</p><h4>PreviewChannelHelper</h4><p>With PreviewChannelHelper<strong>, </strong>you have out-of-the-box implementations of the most common <strong>CRUD</strong> operations with channels and programs. It is an abstraction layer on top of the low-level operations that can be performed with the ContentResolver. Take a look at <a href="https://developer.android.com/reference/androidx/tvprovider/media/tv/PreviewChannelHelper">the documentation</a> for the available functions.</p><p>When reading channel data with the PreviewChannelHelper, you can only read the columns listed on the PreviewChannelHelper.Columns.PROJECTION array which are:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38772f635c06d50d259526ccbe04cc23/href">https://medium.com/media/38772f635c06d50d259526ccbe04cc23/href</a></iframe><p>A channel has <strong>plenty more attributes</strong> than this. Take a look at the getProjection() function in its <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:tvprovider/tvprovider/src/main/java/androidx/tvprovider/media/tv/Channel.java;l=563-618;drc=7091d83302abf98539aec9d89e10723bdf1267a5">source code</a> to see all the existing attributes.</p><p>A very useful attribute is the Channels.COLUMN_BROWSABLE, which indicates if the channel is already published or not. With that, you can show or hide a button to remove the channel from the TV home screen from inside your app. To query that value from the database though, you must use the ContentProvider.</p><p>💡 <strong>Tip</strong>: To avoid frustrations and lost time debugging things like a channel property value not making sense, e.g., a channel that is already published having the Channel.isBrowsable property being false, be aware that the PreviewChannelHelper fills the Channel instance variables with the result of the query from the PROJECTION shown above, which has very limited information. <strong>In other words, properties not listed on the projection will have the field default value </strong>(false for booleans, 0 for numbers, and so on…)</p><h4>ContentProvider</h4><p>Using the ContentProvider APIs gives you full control of the data you want to query. If you want, for example, to query all attributes from a channel you can do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03009a5801d90968bea5f3917bc3dee5/href">https://medium.com/media/03009a5801d90968bea5f3917bc3dee5/href</a></iframe><p>💡 <strong>Tip</strong>: Check the implementations of PreviewChannelHelper functions and adjust them for your needs.</p><h3>Creating or Updating a Program</h3><p>In the same way we manage channels, managing programs is very similar. Look at how we can create or update an existing program and add it to a channel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614d86649c007eeb1f76ee5ed7ee61fc/href">https://medium.com/media/614d86649c007eeb1f76ee5ed7ee61fc/href</a></iframe><p>💡 <strong>Tip</strong>: Notice the call to PreviewProgram.Builder.setInternalProviderId() function. It follows the same logic as the channel builder by providing a way to store the app internal content id into a program.</p><p>⚠️ <strong>Attention</strong>: TheContentProvider CRUD operations are I/O operations. To have the best performance on your app, make sure you are running these operations outside the main thread.</p><p>To wrap up the program management section, check out the implementation of the getChannelPrograms() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68dbc8bde968a4e22b5f88fba11f5259/href">https://medium.com/media/68dbc8bde968a4e22b5f88fba11f5259/href</a></iframe><h3>Handling User Actions on programs and channels</h3><p>Handling user actions is basically handling <a href="https://developer.android.com/training/app-links">App Links</a>. When the user clicks on a channel or program, an Intent will be sent to your app with the URI provided on the channel/program creation. After that, it&#39;s basically navigating to that piece of content on your app.</p><p>Start by adding an &lt;intent-filter&gt; to an &lt;activity&gt; on your app&#39;s AndroidManifest.xml like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6eed67b973fb7882b6e3cd7ad7883da/href">https://medium.com/media/e6eed67b973fb7882b6e3cd7ad7883da/href</a></iframe><p>And add some code to handle the Intent on your Activity or Fragment for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e85bddd86ae018b463fce668c04304be/href">https://medium.com/media/e85bddd86ae018b463fce668c04304be/href</a></iframe><h3>That&#39;s another wrap!</h3><p>If you got to this point, thank you for reading this post! I&#39;m sure you&#39;re striving to build (or already built) an awesome app for your users!</p><p>Follow me to be notified about the next posts. You can also reach me on Twitter with questions or suggestions at @admqueiroga</p><p>Check out one of my other posts about Android TV Leanback development:</p><p><a href="https://proandroiddev.com/android-tv-leanback-playback-controls-part-1-cfbb938a2b89">📺 Android TV Leanback: Playback Controls — Part 1</a></p><p><strong>Additional resources</strong>:</p><ol><li>Make sure to surf through <a href="https://developer.android.com/training/tv/discovery/recommendations-channel">the official and amazing documentation</a> on channels. There&#39;s a lot of knowledge in there.</li><li>Check out <a href="https://developer.android.com/codelabs/tv-recommendations-kotlin?hl=en#0">the channels codelab</a>.</li><li>Check the <a href="https://developer.android.com/training/app-links">App-Links documentation</a>.</li><li>Take a look at the <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/ChannelSample">sample app</a> I used to learn and get inspiration for this post.</li></ol><p><strong>See you soon!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52621502e996" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-tv-preview-channels-a-beginners-guide-52621502e996">📺 Android TV Preview Channels: A Beginner&#39;s Guide</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Android TV Leanback: Playback Controls — Customizing Controls]]></title>
            <link>https://proandroiddev.com/android-tv-leanback-playback-controls-customizing-controls-f543e5a20627?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f543e5a20627</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-tv]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 12:19:04 GMT</pubDate>
            <atom:updated>2023-02-06T17:57:07.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>📺 Android TV Leanback: Playback Controls — Part 2. Customize!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tYSTNtkbTlfWxsdT" /><figcaption>Photo by <a href="https://unsplash.com/@willyin?utm_source=medium&amp;utm_medium=referral">yinka adeoti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the first part of this series, we learned about the building blocks of media playback and control using the <strong>Android Leanback </strong>library and how to add and handle the basic playback controls. We also enhanced the UX of our App by following Google’s <a href="https://developer.android.com/training/tv/playback/controls"><em>Playback controls on TV</em></a> recommendations.</p><p><a href="https://admqueiroga.medium.com/android-tv-leanback-playback-controls-part-1-cfbb938a2b89">📺 Android TV Leanback: Playback Controls — Part 1</a></p><p>Now that we have a better understanding of how to control our media playback and handle control actions, let&#39;s improve our controls by adding a <strong>video thumbnail</strong> close to the content information, a <strong>secondary actions</strong> row with shuffle, repeat, and a &quot;my list&quot; action, and the <strong>&quot;Up Next&quot; row</strong>.</p><h3>Video Thumbnail 🖼</h3><p>Sometimes, it&#39;s easier to remember what we were watching by looking at the thumbnail of a video than by remembering the video title. That&#39;s the idea behind having this visual information in our controls UI.</p><p>To add the movie thumbnail, <strong>we first need a way to load it</strong>. We&#39;ll be using <a href="https://bumptech.github.io/glide/"><em>Glide</em></a>, a fast and well-known image-loading library for Android but feel free to use the library of your choice. The goal is to load a bitmap to pass it to our controls.</p><p>After loading the bitmap, you need to call PlaybackControlsRow.setImageBitmap(). Inside your PlaybackTransportControlGlue, you have access to the controls row instance. Here&#39;s the <a href="https://bumptech.github.io/glide/"><em>Glide</em></a> example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/613b6c8e038cac92ab40258328923c42/href">https://medium.com/media/613b6c8e038cac92ab40258328923c42/href</a></iframe><p>Make sure to call the host.notifyPlaybackRowChanged() so the host can update the PlaybackControlsRow and display the thumbnail. Otherwise, the thumbnail won&#39;t appear.</p><h4>Overriding dimension attributes</h4><p>You can <strong>customize the thumbnail size</strong> by overriding the <strong>Leanback</strong> <strong>resource</strong> used to set its height. Add a new &lt;dimen&gt; resource to your resource files named lb_playback_transport_image_height with the height of your choice in dp.</p><pre>&lt;resources&gt;<br>  &lt;dimen name=&quot;lb_playback_transport_image_height&quot;&gt;120dp&lt;/dimen&gt;<br>&lt;/resources&gt;</pre><p>If you need to go even further in the customization of your controls UI, take a look at the <strong>layout </strong>file<strong> </strong>called lb_playback_transport_controls_row. If you don&#39;t know how to locate it on Android Studio, quickly press &lt;<strong>shift&gt;</strong> twice and type the layout name. Make sure to check the &quot;<strong>include non-project items</strong>&quot; checkbox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-zANT2KO7KV--NBDakDS7A.png" /></figure><p>You will see many @dimen properties like <strong>margins</strong>, <strong>paddings</strong>, and <strong>heights</strong> that you can override the same way we did with the lb_playback_transport_image_height.</p><p><strong>Note:</strong> This approach of overriding resources extends to any resource of your project. If you want to override the entire lb_playback_controls_row layout, go for it. In this case, ensure you create a correspondent layout with the same android:id&#39;s to the correspondent views so the <strong>Leanback</strong> components can find and configure those views.</p><h3>Secondary Controls 🎛</h3><p>To extend our control abilities, we can override the PlaybackTransportControlGlue.onCreateSecondaryActions() and add more actions to the adapters in the same way we did with the primary actions. The secondary actions are displayed right below the seek bar. This means we have plenty of space to add extra actions.</p><p>We&#39;ll add a few built-in actions, <strong>repeat</strong>, <strong>shuffle</strong>, and <strong>thumbs up</strong>, and create a customized &quot;<strong>my list</strong>&quot; action.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d56dfbb0d0ce93b161c9d67798b95c1/href">https://medium.com/media/6d56dfbb0d0ce93b161c9d67798b95c1/href</a></iframe><p>On the thumbsUpAction, we are setting the thumbsAction.index to INDEX_OUTLINE. Visually, this shows an outlined button, i.e., the movie was not liked yet. It&#39;s the opposite of setting to INDEX_SOLID, where the button is filled.</p><p>We&#39;ll do something very similar with our custom MyListAction by creating a MultiAction, which is the base class for actions with multiple states — like filled, outlined, or whatever is our needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bbb88cb7fec559fd687fbd6368cd2d3/href">https://medium.com/media/3bbb88cb7fec559fd687fbd6368cd2d3/href</a></iframe><p>Notice that we added the <strong>add </strong>and<strong> </strong>the<strong> remove </strong>drawable to our action in the same indexes we declared the INDEX_ADD = 0 and INDEX_REMOVE = 1. These indexes must match the indexes of the action drawable and label. Otherwise, its UI won&#39;t be updated as we expect when interacting with the button.</p><p>Last, we will create a function called onSecondaryActionsPressed() to <strong>handle all secondary actions</strong> and then update the PlaybackTransportControlGlue.onActionClicked()to dispatch the new actions click to this function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ec08f434b2fc7020d187d3666e054f/href">https://medium.com/media/b5ec08f434b2fc7020d187d3666e054f/href</a></iframe><p><strong>Notice</strong> that we are checking if the action is a MultiAction, which will always be true for the secondary actions. We increment its index and call the notifyItemChanged(). This code updates the action UI to correspond with the new state (specified by the new index).</p><p>Feel free to check the <a href="https://github.com/ademirqueiroga/leanback-samples/blob/main/transport-controls/tv/src/main/java/me/admqueiroga/transportcontrols/playback/AwesomeTransportControlGlue.kt">sample app</a> if you&#39;re interested in the repeat and shuffle implementations (it&#39;s worth it).</p><h3>Up Next movies row 🎥</h3><p>Let&#39;s provide our users with a better way to navigate its movie playlist. Instead of them having to go back and forth to check what&#39;s the next piece of content, let&#39;s add a row of movies similar to what we have on the app&#39;s main screen. Our goal is to make the controls look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rJSKuH7lnd3sO3AkTKfI-g.gif" /><figcaption>Playback controls with Up Next movies row</figcaption></figure><p>The first thing we need to add a regular ListRow to our controls is to ensure our PlaybackSupportFragment.adapter also supports ListRow&#39;s. We need to add a ListRowPresenter to the adapter PresenterSelector and then add the &quot;<strong>Up Next</strong>&quot; movies list row like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb8e57b64d39bcc7bc92c507633e050e/href">https://medium.com/media/fb8e57b64d39bcc7bc92c507633e050e/href</a></iframe><p>Make sure to keep a reference of the upNextAdapter so you can update its items whenever needed by calling the setItems() function.</p><pre>upNextAdapter.setItems(newPlaylist, MovieDiffCallback)</pre><p>After that, the only missing part is to handle the click on the &quot;<strong>Up Next</strong>&quot; row items. The VideoSupportFragment and any subclass of PlaybackSupportFragment already have a listener for that. Call the setOnItemViewClickedListener() after your fragment is created and handle the click.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29420779b8e4b1d03bdcf563ab24100e/href">https://medium.com/media/29420779b8e4b1d03bdcf563ab24100e/href</a></iframe><h3>That&#39;s another wrap!</h3><p>Thanks again for reading! Follow me to be notified when the next story comes out. Make sure to check the sample app source code <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/transport-controls">here</a>.</p><p>Feel free to check another post covering how to update items on a RowsSupportFragment.</p><p><a href="https://admqueiroga.medium.com/android-tv-leanback-updating-rows-in-rowssupportfragment-b407dff3be4d">📺 Android TV Leanback: Updating Rows in RowsSupportFragment</a></p><p>Questions or suggestions? Reach me on Twitter <a href="https://twitter.com/admqueiroga">@admqueiroga</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f543e5a20627" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-tv-leanback-playback-controls-customizing-controls-f543e5a20627">📺 Android TV Leanback: Playback Controls — Customizing Controls</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Android TV Leanback: Playback Controls — Part 1]]></title>
            <link>https://proandroiddev.com/android-tv-leanback-playback-controls-part-1-cfbb938a2b89?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbb938a2b89</guid>
            <category><![CDATA[tv-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-tv]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 13:21:30 GMT</pubDate>
            <atom:updated>2023-02-08T13:09:59.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>📺 Android TV Leanback: Playback Controls — Part 1. The Basics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l3bg_IkV1pEIRwlp" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are developing a media app, you will certainly need a way to control your content playback, and it&#39;s no different on Android TV.</p><p>This will be a two-part series where we&#39;ll learn how to use the <a href="https://developer.android.com/jetpack/androidx/releases/leanback"><strong>Leanback APIs</strong></a> to implement and customize the transport controls, i.e., media controls and their related content, handle <strong>D-Pad</strong> key events following Google&#39;s <a href="https://developer.android.com/training/tv/playback/controls"><em>Playback controls on TV</em></a> guidelines, and how you can organize your code without mixing UI and playback logic.</p><p>You can find the source code of a sample app applying all the concepts in this series <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/transport-controls">here</a>.</p><h3>Building blocks 🔨</h3><p>The <strong>Leanback</strong> library gives us a good starting point with out-of-the-box implementations to play and control media in our apps. We will use and extend the behavior of the following APIs.</p><h4>VideoSupportFragment</h4><p>A subclass of <a href="https://developer.android.com/reference/androidx/leanback/app/PlaybackSupportFragment"><strong>PlaybackSupportFragment</strong></a><strong>, </strong>which is<strong> </strong>responsible for displaying playback controls and media.</p><p>Like other Leanback fragments, it has an <strong>ObjectAdapter</strong> with a <strong>PresenterSelector</strong> that initially only supports <strong>PlaybackControlsRows</strong>. It is also the entry point of <strong>InputEvents </strong>sent by the user; this is an essential point as we&#39;ll need to intercept these events later to customize the control&#39;s behavior. Here&#39;s a preview of how it can look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXwvep8rcWHSqwxbPt5G3w.png" /><figcaption>VideoSupportFragment with visible controls</figcaption></figure><p><strong><em>Note:</em></strong><em> </em>In the second part of the series, we&#39;ll learn how to support regular <strong>ListRows </strong>and display a list of &quot;Up next&quot; videos below the controls.</p><h4>MediaPlayerAdapter</h4><p>It extends <a href="https://developer.android.com/reference/androidx/leanback/media/PlayerAdapter"><strong>PlayerAdapter</strong></a><strong>, </strong>an abstract class that wraps the media player. It is responsible for receiving events from the UI and performing the associated action onto the underlying player, e.g., plays or pauses the playback. Similarly, it receives events from the player and notifies the UI about its state.</p><p>The <a href="https://developer.android.com/reference/androidx/leanback/media/MediaPlayerAdapter"><strong>MediaPlayerAdapter</strong></a><strong> </strong>comes with several handy implementations, such as playing/pausing content, seeking, preparing the player for playback, and retrieving helpful information like content duration, current playback position, buffering state, and so on.</p><h4>PlaybackControlGlue</h4><p>To connect our UI with the player, the Leanback library provides this fancy &quot;glue&quot; called <a href="https://developer.android.com/reference/androidx/leanback/media/PlaybackControlGlue"><strong>PlaybackControlGlue</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPhVuuPJDlAZkSd_nlhwOA.png" /><figcaption>Source: <a href="https://developer.android.com/training/tv/playback/transport-controls#glueing_the_pieces_together">Glueing the pieces together</a></figcaption></figure><p>Suppose, at first, it was hard to understand this diagram (I needed some time to understand it, mainly due to the &quot;glue host&quot; concept). In that case, you can think of the glue host as an abstraction layer to decouple the glue strictly from the <strong>PlaybackSupportFragment. </strong>This way, we can stick the &quot;left side&quot; of our glue on any class that extends <strong>PlaybackGlueHost</strong> and still communicate and receive all the triggered callbacks by the player.</p><p>As we saw earlier, the controls UI is drawn on the <strong>PlaybackSupportFragment, </strong>but the glue configures and updates it, reflecting the player state. From setting up the correct <strong>Presenter </strong>to display the <strong>PlaybackControlsRow </strong>to updating the progress bar periodically and a lot more, it&#39;s all bonded to the glue. (pun intended)</p><h3>Leanback Assemble! 🛠</h3><p>It&#39;s time to stick the pieces together. Before implementing, please take a look at the <a href="https://developer.android.com/training/tv/playback/controls"><em>Playback controls on tv</em></a><em> </em>guidelines, as we&#39;ll write our code accordingly.</p><h4>BasicMediaPlayerAdapter</h4><p>To dispatch the basic media actions to the underlying player, we’ll extend the <strong>MediaPlayerAdapter </strong>and<strong> </strong>override the five functions below. The play() and pause() functions are already implemented by the <strong>MediaPlayerAdapter.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f57bf81dbada9f36f8bfcf20ab6fc062/href">https://medium.com/media/f57bf81dbada9f36f8bfcf20ab6fc062/href</a></iframe><p>Don&#39;t worry about the rewind() or fastForward() seeking a position outside the content boundaries, i.e., a negative position or a position greater than the media duration. These scenarios are already taken care of by the <strong>MediaPlayer</strong>.</p><p>To keep things simple, our <strong>BasePlayerAdapter </strong>holds a movie playlist, and due to the implementation of our next() and previous() functions, it acts like a circular playlist. If we&#39;re at the last item and next() is called, the first movie will be played. Similarly, the same idea applies to previous().</p><h4>BasicTransportControlGlue</h4><p>We can split our glue implementation into two parts. First, we&#39;ll add buttons for the actions supported by our <strong>BasePlayerAdapter, </strong>handle the clicks, and display the content information. Second, following the guidelines, we&#39;ll intercept the <strong>D-Pad right </strong>and<strong> left</strong> events when the controls UI are hidden to seek forward and backward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d35b1f5fd79977137f3a1643ffa830e/href">https://medium.com/media/5d35b1f5fd79977137f3a1643ffa830e/href</a></iframe><p>With that, your controls should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*rt4CFerEvwYIFnfkTg9UpA.png" /></figure><p>We still need some code to bind the movie information to the UI. We&#39;ll do that by setting the glue <strong>title</strong> and <strong>subtitle</strong> as soon as the player loads the movie (this can be done as quickly as you have the movie information, though). We will also add functions to update our PlayerAdapter playlist and load the movie so that <strong>our fragment only interacts with the glue </strong>instead of directly accessing the <strong>PlayerAdapter.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df1f52e02354bc3625c034e050abac18/href">https://medium.com/media/df1f52e02354bc3625c034e050abac18/href</a></iframe><p><em>Voilà!</em> We have fully operational controls!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8nwSWTUS3tFNX4P5qdkhnQ.gif" /></figure><p>Last but not least, we&#39;ll intercept the <strong>D-Pad</strong> events to perform the forward and rewind actions in the following way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffe1b4ad9a8201f779bbac3bcc87408d/href">https://medium.com/media/ffe1b4ad9a8201f779bbac3bcc87408d/href</a></iframe><p>Notice the initial if condition. The left side is easy to get; the second part though event.repeatCount &gt; 0 , is to detect if the user is <strong>holding </strong>a button which, in this case, we should delegate to the superclass as we only want to intercept single <strong>right/left</strong> clicks. If the user holds one of these buttons, he probably wants to scrub the seek bar.</p><p><strong><em>Note</em></strong><em>:</em> In part 2, we&#39;ll learn how to customize the controls UI with the movie thumbnail.</p><h4>PlaybackVideoFragment</h4><p>In the <strong>PlaybackVideoFragment, </strong>we&#39;ll instantiate the glue and player adapter and connect them with the fragment. We will set the movie playlist and customize the UI to have an <strong>animated indicator when forwarding/rewinding</strong> when the controls are not showing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7351a3616c64238f3598f36233c8343/href">https://medium.com/media/f7351a3616c64238f3598f36233c8343/href</a></iframe><p>We must also intercept the <strong>D-Pad right </strong>and<strong> left </strong>to animate the UI indicators when forwarding/rewinding. Add the following code to the end of your fragment onCreate :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c56c43e60fe872f64fb0d0ffa0c8e1/href">https://medium.com/media/93c56c43e60fe872f64fb0d0ffa0c8e1/href</a></iframe><p>Following the same logic we have on the glue, if the controls are visible or the user is holding a button, we allow the controls to appear by calling isShowOrHideControlsOverlayOnUserInteraction = true , and then we forward the event to the glue. Otherwise, we should not allow the controls to appear on the right/left click until we receive a KeyEvent.ACTION_UP .</p><p><strong>Notice that we intercept the event but act only on the UI level. The glue will act on the player level as we still forward the event to the glue.</strong></p><p><a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/transport-controls/tv/src/main/res/layout">Here</a>, you can find the <strong>XML</strong> layout files for the forward/rewind indicators. The animateIndicator() implementation is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100d7bd82585cb4b02bacf93a0fdf198/href">https://medium.com/media/100d7bd82585cb4b02bacf93a0fdf198/href</a></iframe><p><strong>Here&#39;s the final result!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wdppL13RnygM_pVDaL6fSw.gif" /></figure><h4>That&#39;s a wrap!</h4><p>Thanks for reading! Follow me to be notified about part 2, where we&#39;ll add secondary actions like shuffle and repeat mode, customize the controls <strong>PlaybackRowPresenter</strong> to display the movie thumbnail, and add an &quot;Up Next&quot; content section.</p><p>Make sure to check the sample app source code <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/transport-controls">here</a>.</p><p>Continue learning on part 2!</p><p><a href="https://proandroiddev.com/android-tv-leanback-playback-controls-customizing-controls-f543e5a20627">📺 Android TV Leanback: Playback Controls — Customizing Controls</a></p><p>Questions or suggestions? Reach me on Twitter <a href="https://twitter.com/admqueiroga">@admqueiroga</a></p><h4>Check the official docs at:</h4><p><a href="https://developer.android.com/training/tv/playback/transport-controls">https://developer.android.com/training/tv/playback/transport-controls</a><br><a href="https://developer.android.com/training/tv/playback/controls">https://developer.android.com/training/tv/playback/controls</a></p><p>📺 New to Android TV development? Get started <a href="https://developer.android.com/training/tv/start/start">here</a>!</p><p>See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbb938a2b89" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-tv-leanback-playback-controls-part-1-cfbb938a2b89">📺 Android TV Leanback: Playback Controls — Part 1</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Android TV Leanback: Updating Rows in RowsSupportFragment]]></title>
            <link>https://proandroiddev.com/android-tv-leanback-updating-rows-in-rowssupportfragment-b407dff3be4d?source=rss-7bebee1b1c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/b407dff3be4d</guid>
            <category><![CDATA[diffutil]]></category>
            <category><![CDATA[android-leanback]]></category>
            <category><![CDATA[android-tv]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Ademir Queiroga]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 17:47:37 GMT</pubDate>
            <atom:updated>2023-02-06T16:40:50.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w8r5UVpucM228lap" /><figcaption>Photo by <a href="https://unsplash.com/@claybanks?utm_source=medium&amp;utm_medium=referral">Clay Banks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the challenges I faced when I started developing Android TV apps was the lack of documentation around some more specific tasks—for example, updating the content of a list of <strong>ListRows</strong> without having the whole <strong>ListRow</strong>, or the entire screen blinking. When you have a <strong>RecyclerView</strong> with dynamic content, it&#39;s a good practice, for performance and UX, that the list updates trigger only the least amount of work on the device and avoid janks on the UI.</p><p>In this post, we&#39;ll learn how to update the rows of a <strong>RowsSupportFragment</strong> leveraging the power of the <strong>DiffUtil</strong> class and how to update only the specific content that changed in the row. <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/rows-update">Here</a>, you can find a sample app applying all the concepts covered in this post.</p><h3>The <strong>problem ⚠️</strong></h3><p>Below we have a very common UI for Android TV apps, a vertical list of horizontal lists. This screen extends the <strong>RowsSupportFragment</strong> from the leanback library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzKHC6JT5XEx2ozauOi6hA.png" /><figcaption><a href="https://github.com/ademirqueiroga/leanback-samples/blob/main/rows-update/app/src/main/java/me/admqueiroga/example/MovieRowsFragment.kt">MovieRowsFragment</a></figcaption></figure><p>The problem surfaces when the rows have dynamic content. As an example, Live events that are frequently updated to reflect the Live status or are removed if ended. Another situation is if you want to keep the <strong>selected item scroll position </strong>after performing the update (Only possible if the selected item is also present after the update).</p><p>If you try to update your row by just changing the content of the adapter, you will end up with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bDfRv6JTLZwwtPMi-B9dsg.gif" /><figcaption>Blink when updating rows</figcaption></figure><h3><strong>The solution 💡</strong></h3><p>To avoid these blinks when updating the rows, we need to tell the <strong>ListRowPresenter</strong> which and what changed between the old and new rows we want to display. To achieve that, we can implement a <strong>DiffCallback</strong> that compares both rows and detect these changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd19bc90cc380743fbdb5614337f366a/href">https://medium.com/media/dd19bc90cc380743fbdb5614337f366a/href</a></iframe><p>Now that we have a <strong>DiffCallback</strong> that detects the changes between our rows, we can update the items of a <strong>RowsSupportFragment </strong>adapter<strong> </strong>like the following:</p><pre>(rowsAdapter as ArrayObjectAdapter).setItems(newRows, MovieListRowDiffCallback)</pre><p>The advantages of passing the <strong>DiffCallback </strong>instead of<strong> null </strong>when<strong> </strong>setting the items<strong> </strong>of an<strong> ArrayObjectAdapter </strong>are that only the required <strong>notify </strong>calls will be dispatched to it<strong> </strong>(instead of a full <strong>notifyDataSetChanged</strong>) and that we&#39;ll be able to handle the specific changes in isolation in the <strong>ListRowPresenter</strong>.</p><p>If you run the app after these changes, you might wonder why nothing has changed. That&#39;s because we still need to handle the content update in our <strong>ListRowPresenter. </strong>Specifically, we need to override the overload of the <strong>onBindViewHolder </strong>that receives a list as its third parameter, the <strong>payloads </strong>argument, containing all the data changes returned by the <strong>DiffCallback.</strong></p><p>Remember, at this point, we are binding a <strong>ListRow</strong> which consists of only a <strong>HeaderItem </strong>and an <strong>Adapter, </strong>so the only operations we can do are:</p><ol><li>Update the row<strong> title.</strong> We can do so by using the <strong>headerPresenter </strong>and<strong> </strong>binding the new item to the ListRow.</li><li>Update the row<strong> items.</strong> We can do this by accessing the row adapter and using its <strong>setItems</strong> function.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e28217694ba64b19a31d0c476b0538bf/href">https://medium.com/media/e28217694ba64b19a31d0c476b0538bf/href</a></iframe><p>Notice that when updating the row <strong>items,</strong> we also need to provide a <strong>DiffUtil </strong>implementation responsible for comparing the items of that row. Otherwise, we would still trigger a full <strong>notifyDataSetChanged </strong>in<strong> </strong>the<strong> </strong>row adapter, and there will be no visual difference.</p><p>After that, the <strong>row items adapter</strong> will receive only the correct notify calls, and we will end up with this smooth animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ApKzewFfwGwpljwZcIEoFg.gif" /><figcaption>Animate when updating rows</figcaption></figure><h4>Remember!</h4><ul><li>ListRows are just a <strong>HeaderItem</strong> with an <strong>ObjectAdapter.</strong></li><li>Your ListRows are the items of the <strong>RowsSupportFragment </strong>adapter<strong>.</strong></li><li>To update a <strong>ListRow</strong> leveraging all the <strong>RecyclerView </strong>optimizations,<strong> </strong>you will need to:<br>1. Use a <strong>DiffCallback</strong> to <strong>detect which and what rows changed</strong>.<strong><br></strong>2<strong>. </strong>Perform the updates on your <strong>ListRow</strong> based on the <strong>DiffCallback.getChangePayload</strong> return.</li></ul><p>You can find the sample app with the complete implementation <a href="https://github.com/ademirqueiroga/leanback-samples/tree/main/rows-update">here</a>.</p><h3>That&#39;s all</h3><p>For now… thanks for reading! This was the first of many posts I&#39;ll write about Android TV development.</p><p>Questions or suggestions? Reach me out on on twitter @admqueiroga</p><p>📺 New to Android TV development? Get started <a href="https://developer.android.com/training/tv/start/start">here</a>!</p><p>See ya!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b407dff3be4d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/android-tv-leanback-updating-rows-in-rowssupportfragment-b407dff3be4d">📺 Android TV Leanback: Updating Rows in RowsSupportFragment</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>