<?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 Tai Than on Medium]]></title>
        <description><![CDATA[Stories by Tai Than on Medium]]></description>
        <link>https://medium.com/@thanductaimgt?source=rss-528ff71bf137------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*95s50hRn_2qHvhQni_AjTw.jpeg</url>
            <title>Stories by Tai Than on Medium</title>
            <link>https://medium.com/@thanductaimgt?source=rss-528ff71bf137------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:48:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thanductaimgt/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[Improve scrolling performance of a ViewPager with complex layout Fragment items]]></title>
            <link>https://medium.com/@thanductaimgt/improve-scrolling-performance-of-a-viewpager-with-complex-layout-fragment-items-660ab56ea773?source=rss-528ff71bf137------2</link>
            <guid isPermaLink="false">https://medium.com/p/660ab56ea773</guid>
            <category><![CDATA[profile]]></category>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[viewpager]]></category>
            <dc:creator><![CDATA[Tai Than]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 11:47:31 GMT</pubDate>
            <atom:updated>2022-02-14T04:41:29.270Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, this is my second post about improving Android app performance. If you want to check out my first post, reducing video preparing time in a video playlist, here is the link:</p><p><a href="https://medium.com/@thanductaimgt/pre-caching-adaptive-video-stream-in-a-playlist-with-exoplayer-api-5ef92097d94e">Pre-caching adaptive video stream in a playlist with ExoPlayer API</a></p><p>In this post, we will be discussing about how to improve scrolling performance of a <em>ViewPager</em> (or <em>ViewPager2</em>), which host a list of <em>Fragment</em>s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1ehfDW0B3QTXGS3mYOIRQ.png" /></figure><h3>1. Analysis:</h3><p>Firstly, we will be analyzing on what can cause lag issue while scrolling on a <em>ViewPager</em>. There are various tools that we can use to profile UI performance of an Android app. I personally prefer using <a href="https://ui.perfetto.dev/"><strong>Perfetto UI</strong></a>. It’s a handy tool with web interface for analyzing trace files from many sources, including Android system trace. Refer to this <a href="https://developer.android.com/topic/performance/tracing/on-device">link</a> to learn how to collect Android system trace file.</p><p>The use case I have profiled is the video list screen of my company app. It’s a <em>ViewPager2</em> with <em>Fragment</em> items, each <em>Fragment</em> has a very complex layout. While scrolling on the video list, I usually experience janky (lag) issue, so I profiled the video list for a short period during which I scrolled for about 2 or 3 pages. Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3zjAdVma4Yjvexl" /><figcaption>Profiling result before improving</figcaption></figure><p>From the profiling result above, we can see that at the time I scroll the video list, <em>doFrame()</em> method is invoked on the main thread, and it took about <strong>231ms</strong> to complete. During this period the UI is blocked, so many frames could not be rendered to the screen. Even worse, this happened while scrolling which cause the page transition animation to be extremely lag.</p><p>A big part of the work that took place during <em>doFrame()</em> is inflating layout. As the layout of a <em>Fragment</em> item is complex, it took <strong>82ms</strong> to inflate. Also, because a <em>ViewPager</em> has no mechanism no reuse/recycle <em>Fragment</em> items like a <em>RecyclerView</em>, layout inflation will continue to occur and the problem will remain every time I scroll to a new page.</p><p>From the profiling result, I had considered some improvement ideas as below:</p><ul><li><strong>Reduce inflation count</strong>: can be achieve by using <em>ViewPager2</em> with <em>View</em> items, instead of a <em>Fragment</em> items as we can utilize the built-in mechanism to recycle pages’ layout, there by eliminating the need for inflating layout again for the subsequent pages. Unfortunately, this idea is not applicable to my video list as the bindings to Fragment’s lifecycle methods are already too complex for me to refactor to using View items.</li><li><strong>Reduce inflation time</strong>: This can be achieved by applying lazy inflation to some parts of the <em>Fragment</em> layout. View lazy inflation can be implemented using <a href="https://developer.android.com/reference/android/view/ViewStub"><em>ViewStub</em></a> together with <a href="https://developer.android.com/reference/androidx/asynclayoutinflater/view/AsyncLayoutInflater"><em>AsyncLayoutInflator</em></a><em>. </em>I have tried this approach but the improvement is not so significant as there are not many things in my video list that can be lazily inflated.</li><li><strong>Inflate layout at a suitable time</strong>: as layout inflation occurs while scrolling the video list, lag issue is more noticeable to the user. Therefore, it’s better to somehow move the inflation work to another time, when the <em>ViewPager</em> is already idle. After many attempts, I successfully implemented this idea of using <em>ViewPager.offScreenPageLimit</em> attribute in a tricky way. Below is the implementation details and the result of my improvement.</li></ul><h3>2. Implementation</h3><p>The number of pages of a <em>ViewPager</em> can be arbitrarily large, so not all of its <em>Fragment</em> item will be kept in the memory. In fact, only a number of pages adjacent to the currently focused page of the <em>ViewPager</em> are kept as they have the highest chance to be chosen to display next on the screen. <em>ViewPager.offScreenPageLimit</em> is the attribute to set this number.</p><p>The default page-prefetching mechanism of the <em>ViewPager</em> is based on calculating the current gap in pixel from the page to be prefetched to the display screen. If the gap is lower than a bound (proportional to <em>offScreenPageLimit</em>), <em>ViewPager</em> will start prefetching the target page. While scrolling the video list, the target page to be prefetched will become gradually closer to the screen area. The <em>ViewPager</em> will continuously checks for the condition and performs page prefetching, which includes layout inflation, if the condition is met.</p><p>The goal is to make the prefetching condition not to be met while scrolling is taking place. To achieve this, I performed the following steps:</p><ol><li>Set <em>offScreenPageLimit</em> to <strong>n</strong> so that when first entering the video list, <em>ViewPager</em> will prefetch the next <strong>n</strong> pages immediately (choose your suitable <strong>n</strong>, mine is 2).</li><li>When all the pages have been prefetched, set <em>offScreenPageLimit</em> to <strong>n-1</strong>. At this point, if user scrolls to the next page, the prefetching condition won’t be met as the bound has been lowered in respect of the new <em>offScreenPageLimit</em>.</li><li>When user has finished scrolling to the next page, i.e. the <em>ViewPager</em> is idle, back to step 1. The <em>offScreenPageLimit</em> is set back to <strong>n</strong>, so that the prefetching condition is met immediately and the target page is prefetched while the video list is idle.</li></ol><p>When applying the above steps repeatedly, the <em>ViewPager</em> will only prefetch a new page when it’s in idle state, and UI blocking due to layout inflation is really hard to be noticed. Other than these mentioned steps, we also need to write more code to handle some edge cases. Please check out the sample repository below for a completely working solution:</p><p><a href="https://github.com/thanductaimgt/improve-scroll-viewpager-sample">GitHub - thanductaimgt/improve-scroll-viewpager-sample: Sample Android app demonstrating improving scrolling performance of ViewPager with Fragment items</a></p><h3><strong>3. Result and conclusion</strong></h3><p>After applying the improvement, I profiled my video list again and got the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TXT5Tma2BU95m5sQ" /><figcaption>Profiling result after improving</figcaption></figure><p><em>doFrame()</em> duration is significantly reduced to <strong>24ms</strong>, about <strong>1/10</strong> of the duration before applying the improvement, and the scrolling is smoother than ever. I can achieve this result because most of the work, which is inflating layout, is move from the time I scroll the video list to the time the video list is idle.</p><p><strong>Demo</strong></p><p>Note: in the demo, improvement took effect after 2 times page swiping, after turned on.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fbravewebbedgarpike&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fbravewebbedgarpike&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FBraveWebbedGarpike-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="620" height="1280" frameborder="0" scrolling="no"><a href="https://medium.com/media/96056667b124d665ece0a927ca291a8f/href">https://medium.com/media/96056667b124d665ece0a927ca291a8f/href</a></iframe><p>To conclude, using lazy layout inflation together with inflating layout when <em>ViewPager</em> is idle help us minimize janky user experience while scrolling the video list. If possible, I recommend that we should use <em>ViewPager</em> with <em>View</em> items as it can recycle its pages, and the prefetching strategy is also more reasonable according to some experiments of mine.</p><p>Thanks for reading this post. The next post will be about minimizing build time for big, multi-module Android projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=660ab56ea773" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pre-caching adaptive video stream in a playlist with ExoPlayer API]]></title>
            <link>https://medium.com/@thanductaimgt/pre-caching-adaptive-video-stream-in-a-playlist-with-exoplayer-api-5ef92097d94e?source=rss-528ff71bf137------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef92097d94e</guid>
            <category><![CDATA[android-performance]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[pre-cache]]></category>
            <dc:creator><![CDATA[Tai Than]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 16:32:57 GMT</pubDate>
            <atom:updated>2021-08-23T16:32:57.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Hi_KZDhdI0lKAgIbmdXhQ.png" /></figure><p>Recently, I have been working on improving video playlist performance for my company Android project. The playlist is a video list that can be scrolled back and forth to change the currently focused video for playing. One of the things I care about is the long wait time after switching to a new video, before it is playable. Video preparing time can be reduced significantly by applying pre-caching mechanism on the videos that are going to be played. However, my company project uses HLS for video streaming, which make it a little bit more complicated to cache video stream. After a while browsing on the Internet, I finally am able to implement it, and now I want to share my implementation with you guys.</p><h3><strong>Analysis</strong></h3><p>The basic idea of pre-caching is to download the beginning of the video that is going to be played into a cache. When the user scrolls to that video, the player will detect that the requested data has already existed in the cache and use it for playback rather than obtaining the data from network. While playing, the player will continuously check to load subsequent video segments from cache and once reaching the end of the cached part, it will seamlessly switch to use network source.</p><p>In the case of adaptive video stream, it is more complicated to implement pre-caching as there are many tracks (options) to choose in each group (video resolution, audio, subtitle, etc.). Pre-caching the beginning of every track is quite an overkill, as the cache size would be unnecessarily huge. Instead, we should only pre-cache a minimal number of tracks which is enough for the video to be playable, i.e. only one track per group. However, this could introduce a different issue that when the player starts preparing the video, it may not choose the exact tracks which has been pre-cached, and may start downloading the tracks that it prefers from the network (check this <a href="https://github.com/google/ExoPlayer/issues/7920">ExoPlayer github issue</a> for more details). To address this issue, we can specify specific tracks to pre-cache, then force the player to choose these tracks when it starts preparing the video for playback. This approach may lead to losing the benefit of using adaptive stream as we prevent the player from dynamically switching between available tracks based on its conditions and constraints, so take it into your consideration. In my case, it’s not that necessary to change the playback option on-the-fly, so it’s fine to apply.</p><h3>Implementation</h3><ol><li><strong>Construct CacheDataSourceFactory instance</strong></li></ol><p>The metadata for the video to be prepared is passed to the player via a <strong>MediaSource</strong> instance (or <strong>MediaItem</strong>, if using newer <strong>ExoPlayer</strong> versions), which can be constructed using a <strong>DataSource.Factory</strong>. Normally, we would simply use a <strong>DefaultDataSourceFactory</strong> to construct a <strong>MediaSource</strong>, which makes the player download the video stream from the network and no caching is applied by default. To construct a data source that can utilize cache, we need to use a <strong>CacheDataSourceFactory</strong> instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ec7fd7a7124db3354a701caa9edfa5/href">https://medium.com/media/67ec7fd7a7124db3354a701caa9edfa5/href</a></iframe><p>To construct a CacheDataSourceFactory, we need to build several parameters including:</p><ul><li><em>cache</em>: a <strong>Cache</strong> instance, an in-memory representation of the storage cache. To construct a <strong>Cache</strong>, we need to provide the path to its location, a <strong>CacheEvictor</strong> and a <strong>DatabaseProvider</strong>. The <strong>File</strong> path should be a dedicated directory for <strong>ExoPlayer</strong>, as it may delete any unrecognized file in the directory. The <strong>CacheEvictor</strong> is responsible for evicting content from the cache based on some strategies. In our case we should use a <strong>LeastRecentlyUsedCacheEvictor</strong> as the cached video stream doesn’t need to stay in the cache permanently. If you prefer otherwise, you can use a <strong>NoOpCacheEvictor</strong> instead. The third parameter, <strong>DatabaseProvider</strong> is for storing the metadata of the cached video, so that they can be managed by the <strong>Cache</strong>. An important note is that there should be only one <strong>Cache</strong> instance operating on a particular directory at a time, since it will lock the directory after being constructed, and further <strong>Cache</strong> instance built with the same directory (before calling <em>cache.release()</em> on the previous <strong>Cache</strong>) will throw a <strong>RuntimeException</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f19ef9be295f1f758a9c70f99ae4c3ae/href">https://medium.com/media/f19ef9be295f1f758a9c70f99ae4c3ae/href</a></iframe><ul><li><em>upstreamDataSourceFactory</em>: a <strong>DataSource.Factory</strong> for obtaining video content from the upstream (network) source, if not found in cache. For simplicity we can use a <strong>DefaultDataSourceFactory</strong>.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b7dd24b6316c0f74d45a29cafe466b/href">https://medium.com/media/73b7dd24b6316c0f74d45a29cafe466b/href</a></iframe><ul><li>The next 3 parameters are <em>cacheReadDataSourceFactory</em>, <em>cacheWriteDataSinkFactory</em> and <em>flags</em>, which are used for reading, writing cache and customizing cache usage strategy respectively. We don’t need much customization on these parameters so I’m gonna use the default manners to construct them. The last parameter is the <em>eventListener</em>, used for debugging the cache.</li></ul><p><strong>2. Build a MediaSource for playing</strong></p><p>The constructed <strong>CacheDataSourceFactory</strong> instance, together with the video stream url will be used to create a new <strong>MediaSource</strong> each time it is required (usually one <strong>MediaSource</strong> per video)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b99ba13e162fc8cbc8225499efe0b141/href">https://medium.com/media/b99ba13e162fc8cbc8225499efe0b141/href</a></iframe><p>When creating a new <strong>MediaSource</strong>, it’s vitally important to set the stream keys for the <strong>MediaSource.Factory</strong>. The stream keys are used to filter the adaptive video stream’s manifest, so that the tracks to be prepared are fixed to the tracks that we are going to pre-cache. This will also prevent the player from switching to the tracks that are not filtered by the stream keys while playing, as long as it still use this <strong>MediaSource</strong> instance. The <strong>StreamKey</strong> first constructor parameter is the group index (index of the resolution, audio, caption, etc. group), and the second one is the track index (the option within each group). The example above assumed that the adaptive video stream has at least 5 groups and 2 tracks per group. By building the <em>cacheStreamKeys</em> as above, we will be caching the track at index 1 (the second track) of each group, for totally 5 groups. Calling <em>setAllowChunklessPreparation()</em> is for enabling chunkless preparation if possible, when the master playlist (manifest) provides sufficient information, to reduce the preparation time.</p><p><strong>3. Pre-cache the video stream</strong></p><p>To pre-cache the video stream, we will be using the APIs provided by the <strong>ExoPlayer</strong> library itself. First we need to construct a <strong>Downloader</strong> used for downloading the video content into the cache. The <em>cache</em>, <em>upstreamDataSourceFactory</em> and <em>cacheDataSourceFactory</em> parameters should be the same instances used for creating the <strong>MediaSource</strong>s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134b38e2092fbf9acbdea3b42ffa62be/href">https://medium.com/media/134b38e2092fbf9acbdea3b42ffa62be/href</a></iframe><p>To pre-cache the video stream, simply call <em>downloader.download()</em> on a worker thread and cancel it when the size of the pre-cached part is large enough. In the example below, I use <strong>kotlin coroutines</strong> for running asynchronous downloading operation in the background.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0153f77ebb3e7ef786225e6a1d22d182/href">https://medium.com/media/0153f77ebb3e7ef786225e6a1d22d182/href</a></iframe><p>This <em>preCacheVideo()</em> method should be invoked for pre-caching the next video in the list, when the user has scrolled to a newly focused one. In addition, pre-caching should be cancelled when the user scrolls to the targeted video, as the <strong>ExoPlayer</strong> will be taking care of downloading more segments while playing this video, and also to prevent potential conflict when both agents may perform write operations to the same cache simultaneously.</p><p>For a detailed implementation, check the source code below:</p><p><a href="https://github.com/thanductaimgt/exo-player-pre-cache-sample">GitHub - thanductaimgt/exo-player-pre-cache-sample: Sample App for pre-caching adaptive video stream with ExoPlayer</a></p><p>Thanks for reading my very first story, please give a clap if you find it useful. Subscribe for more performance improvement tips and tricks on Android app development. The next story will be about improving scrolling performance in a ViewPager with layout-complicated Fragments.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef92097d94e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>