<?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 Roger Erill on Medium]]></title>
        <description><![CDATA[Stories by Roger Erill on Medium]]></description>
        <link>https://medium.com/@roger.erill?source=rss-dbb9e8bb51de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zRzUNLI01ZM8QJRv0csHyw.jpeg</url>
            <title>Stories by Roger Erill on Medium</title>
            <link>https://medium.com/@roger.erill?source=rss-dbb9e8bb51de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:19:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roger.erill/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[Using Firebase Test Lab in multi-module Android projects]]></title>
            <link>https://medium.com/21buttons-tech/using-firebase-test-lab-in-multi-module-android-projects-4bf051868d5e?source=rss-dbb9e8bb51de------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf051868d5e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebase-test-lab]]></category>
            <category><![CDATA[21buttons]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android-testing]]></category>
            <dc:creator><![CDATA[Roger Erill]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 11:53:45 GMT</pubDate>
            <atom:updated>2020-01-28T13:50:50.629Z</atom:updated>
            <content:encoded><![CDATA[<h4>It can be tricky to run your instrumentation tests in CircleCI when your project has several modules. Here we’ll explain a simple way to do it</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YhlV9Vy5TBi6Nv9o" /><figcaption>Photo by <a href="https://unsplash.com/@alexanderkondratiev?utm_source=medium&amp;utm_medium=referral">Alex Kondratiev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re a developer concerned with quality, you surely write tests in your app. When you have a large enough project, executing the tests locally becomes less and less of an option, and normally you rely on a CI system to execute them for you. At <a href="https://play.google.com/store/apps/details?id=com.android21buttons">21Buttons</a>, we are using <a href="https://engineering.21buttons.com/optimizing-your-circleci-pipeline-time-in-android-f040873764e1"><strong>CircleCI</strong></a> to do it. In Android, executing Unit Tests in a CI environment is not difficult, you can just use ./gradlew testDebug. But if you want to execute <strong>instrumentation tests</strong>, it’s not that easy since <a href="https://support.circleci.com/hc/en-us/articles/360000028928-Testing-with-Android-emulator-on-CircleCI-2-0">CircleCI does not support it out of the box</a>.</p><p>To solve this problem, I think that one of the best options is to use <a href="https://firebase.google.com/docs/test-lab"><strong>Firebase Test Lab</strong></a><strong>.</strong> It’s also the one that CircleCI recommends. Let’s see what it is.</p><h4>What’s it?</h4><p>If you don’t know Firebase and you want to know what it is and what’s capable of, I recommend you this <a href="https://proandroiddev.com/firebase-android-series-learning-firebase-from-zero-to-hero-3bacbdf8e048">series of posts</a> that talk about it. There’s even a specific one for <a href="https://proandroiddev.com/firebase-android-series-test-lab-bbcd41104086">Firebase Test Lab</a>.</p><p>To put it in a short way, Firebase Test Lab allows you to <strong>execute your tests</strong> on a cloud automated environment using Google’s infrastructure, where you have a large array of real devices or emulators to use in your tests. In order to use the test lab, you need to create an account in Firebase, have a project on Firebase and set up a <a href="https://circleci.com/docs/2.0/google-auth/#creating-and-storing-a-service-account"><strong>Google</strong> <strong>service account</strong></a><strong>. </strong>This will allow Google to authenticate your app.</p><h4>How much does it cost</h4><p>At the time of this post’s writing, with the <a href="https://firebase.google.com/pricing">free tier</a> you’re allowed to <strong>10 suite tests per day </strong>(5 if using real devices). Each emulator you launch will consume one of these suite tests. If you want to split your tests in several sub-groups to speed up the execution (the so called <a href="https://firebase.google.com/docs/test-lab/android/instrumentation-test#sharding">shards</a>) each shard will count for the quota too. Each module generates a different apk for testing, so it will launch a new test instance every time. In our specific case, we have a big module containing mostly old code, that has about ~400 instrumentation tests in it, and we usually split it in several shards (otherwise we would exceed the time limit), and then about ~20 small modules. You can clearly see that with our setup, we cannot run the tests in the free plan even if it was only once a day.</p><h4>How does Firebase Test Lab work?</h4><p>We won’t get very deep into the specifics on how to test our app using the <a href="https://cloud.google.com/sdk/docs">Google Cloud SDK</a> (<strong>gcloud) </strong>because, with our approach to the problem, we will not need it much. If you take a look at the documentation, you’ll see that the setup is not super straightforward. Fortunately, CircleCI team put up <a href="https://circleci.com/docs/2.0/language-android/#testing-with-firebase-test-lab">some documentation</a> which makes it a bit easier.</p><p>If you have a multi-module project, the <strong>problem</strong> lies in this step:</p><blockquote>Build the debug APK and test APK. Use Gradle to build two APKs.</blockquote><p>Then you would execute a step like:</p><pre>- run: <br>    name: Test with Firebase Test Lab <br>    command: &gt; <br>        sudo gcloud firebase test android run \ <br>           -— app &lt;local_server_path&gt;/&lt;app_apk&gt;.apk \<br>           -- test &lt;local_server_path&gt;/&lt;app_test_apk&gt;.apk \<br>           -— results-bucket cloud-test-${GOOGLE_PROJECT_ID}</pre><p>With this approach, you would have to write this piece of code <strong>for every module you wanted to test, </strong>which can be prone to errors, and not a very extensible solution. But don’t give up yet! We’ll present you with an easier solution to deal with this.</p><h4>The easy way</h4><p>After seeing this problem, we searched for solutions and we found this <a href="https://github.com/piotrmadry/FirebaseTestLab-Android"><strong>Firebase Test Lab Plugin Library</strong></a><strong>. </strong>We saw it was very simple to use and it abstracted you about details on how to use gcloud. To use it we created a gradle script like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b998894bbcaf72cdbac7ba742f8eb5e7/href">https://medium.com/media/b998894bbcaf72cdbac7ba742f8eb5e7/href</a></iframe><p>And then we just add</p><pre>apply from: &quot;$rootProject.projectDir/gradle/with-firebase.gradle&quot;</pre><p>in every module where we want the instrumentation tests to be executed, that way we’re not repeating a lot of code.</p><p>For this to work, previously you will need to have in your project a json file (here named gcloud-service-key.json) that you get when you create a <a href="https://console.cloud.google.com/iam-admin/serviceaccounts">Service Account</a> in Google Cloud Platform. This is a <strong>sensitive file</strong>, so I recommend you not to store it in your repository and let your CI handle it as an environment variable when you need to execute the tests. Here’s an example on how it would look like if we wanted to add this step on CircleCI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deaacaa719e2fb5f88d60dd65d464f16/href">https://medium.com/media/deaacaa719e2fb5f88d60dd65d464f16/href</a></iframe><p>As you can see, we stored our service json file as an <strong>environment variable</strong> in CircleCI and then we pass it to the workspace (the root folder where your code has been checked out before). We also added a no_output_timeout: 2h<em> </em>parameter, this is because in our case, this task can take up a long time to finish and CircleCI will wait 10 minutes after it times out. Even while this task is being executed, you can see your test results at your Firebase Console, under the <em>Test Lab</em> section. Every time a new module has finished its tests, it will appear there.</p><p>And that’s all for us! We hope this post has been helpful to you and… happy testing! 🎊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf051868d5e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/21buttons-tech/using-firebase-test-lab-in-multi-module-android-projects-4bf051868d5e">Using Firebase Test Lab in multi-module Android projects</a> was originally published in <a href="https://medium.com/21buttons-tech">21 Buttons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing your CircleCI pipeline time in Android]]></title>
            <link>https://medium.com/21buttons-tech/optimizing-your-circleci-pipeline-time-in-android-f040873764e1?source=rss-dbb9e8bb51de------2</link>
            <guid isPermaLink="false">https://medium.com/p/f040873764e1</guid>
            <category><![CDATA[21buttons]]></category>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Roger Erill]]></dc:creator>
            <pubDate>Tue, 25 Jun 2019 09:30:06 GMT</pubDate>
            <atom:updated>2019-07-01T10:43:49.346Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some tips and tricks we learnt along the way to make your deploy much faster in Android projects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PT3Gem2QZ_CMWagtvXK63g.jpeg" /><figcaption>This is a pipeline. Ours is a digital one, though. Source: <a href="https://pixabay.com/users/loggawiggler-15/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=509870">LoggaWiggler</a></figcaption></figure><p>Recently, in the Android team at 21 Buttons we have moved away from Jenkins to embrace CircleCI as our platform for CI/CD. This has come with some challenges, like leaving behind a self-hosted solution and adapt to the way CircleCI works.</p><p>As most people working in IT, <strong>we love optimizing things</strong> 😄 so this was also a good opportunity to reduce our pipeline time. In this article we’ll show you how we did it, but if you’re not too familiar with CircleCI, I recommend you to read some articles like <a href="https://medium.com/static-void-academy/easy-peasy-ci-cd-w-circleci-282bc85ddcf5"><strong>this one</strong></a> first to get a better understanding of the platform, because here we’ll not discuss much about CircleCI basics.</p><p>Let’s get into it then! First, I’m going to explain how is our pipeline to better understand the steps we’re going to optimize later on:</p><p><strong>Static analysis → Compile → Unit tests → Generate APK → Deploy</strong></p><p>So, getting into details:</p><ul><li><strong>Static analysis: </strong>We use ./gradlew ktlintCheck detekt to check for formatting issues or code smells</li><li><strong>Unit tests: </strong>./gradlew testDebug</li><li><strong>Compile: </strong>Here things get a little bit more interesting</li></ul><pre>./gradlew compileDebugAndroidTestSources :app:compileDebugSources :app:compileReleaseSource</pre><p>We currently do not execute Android tests in our pipeline (we do it in a nightly schedule) so our pipeline does not get too long (it would add like ~40min to execute them all!). Here we check that at least, the code in those tests compiles. We also compile debug and release to check that all the code is correct.</p><ul><li><strong>Generate APK: </strong>./gradlew :app:assembleRelease (or debug, depending on the situation)</li><li><strong>Deploy: </strong>We use <a href="https://hockeyapp.net/">HockeyApp</a> as a repository to store our generated APK, and the QA team can get the versions from there. Here we use a script that gets the apk and uploads it to HockeyAPP via API. If we need to deploy to Google Play Store, we use a similar script too.</li></ul><p>There are some other minor things, but basically that’s it! We’re going to try to optimize this funnel. For reference, <strong>this pipeline takes ~9 minutes to execute in Jenkins. </strong>Let’s check now with CircleCI.</p><h3>Setting the CircleCI environment</h3><p>Each job runs in an environment, and that is a crucial part on optimizing your pipeline. There are two main things to consider, the <strong>Docker image</strong> and <strong>JVM/Gradle </strong>configurations.</p><p>For jobs that require Android SDK, we tested with the official image from CircleCI <a href="https://hub.docker.com/r/circleci/android"><strong>circleci/android:api-28</strong></a><strong> </strong>and <a href="https://hub.docker.com/r/21buttons/android-builds"><strong>our own image</strong></a><strong> </strong>(code <a href="https://github.com/21Buttons/android-builds/blob/master/Dockerfile">here</a>). Our image is half the size (2GB vs 1GB) but we found out that normally, the CircleCI image is cached in the node much often. We took some data to validate our hypothesis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*VWjZkBcozuNoXeIQ2ywiaw.png" /><figcaption>Histogram showing the occurrences of the image taking S seconds to load</figcaption></figure><p>So, we see at a glance that CircleCI image usually loads in less than 5 seconds, but when it doesn’t, it can take up until 106 seconds to load. In contrast, our image almost always falls on the 20–30 seconds range. The average time to load is roughly <strong>15 seconds </strong>for CircleCI image vs <strong>23.5 seconds </strong>for our image. Therefore, we’ll stick with CircleCI image for now. 😃</p><p>About the JVM/Gradle performance, we soon found out that the standard machine CircleCI offers (2 CPUs and 4GB of RAM) was <strong>insufficient</strong> for our needs, dealing a lot of OOM errors or taking a lot of time at best. We wanted to test with a larger resource class and these are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*mAgqtj7JW2nM_ddW9CsO6g.png" /><figcaption>Comparison of different resource classes in CircleCI</figcaption></figure><p>For compile and assemble tasks, we only measured time spent actually performing the gradle tasks, for overall pipeline we took into account everything (spin-up, persisting to workspace, unit tests…). Notice that after medium, all other perform similarly. We found out that in medium, specially for Assemble phase, there was a lot of time that the JVM was in GC (about 35% of the time), whereas in the other resources it was always at about 2%. In our case, we chose <strong>Large (4 CPUs, 8GB RAM).</strong></p><p>Now for the necessary tweaks in gradle properties, we ended up using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5324241d3c8930f7842e1cec69d9033d/href">https://medium.com/media/5324241d3c8930f7842e1cec69d9033d/href</a></iframe><p>It’s important to <strong>play with the</strong> <strong>jvmargs</strong> to get a value that’s not too high or low. 3GB of memory worked for us. It’s important to disable gradle daemon since this is only beneficial for subsequent builds and here each job will only run one gradle task. The same for kotlin incremental, and for workers, make sure they not exceed your machine’s CPUs.</p><h3>Creating our workflow</h3><p>Once we decided the environment in which we’ll run our jobs, it’s time to think our workflow and see how can we benefit from parallelism. We will cover different approaches here:</p><h4>1. The monolithic approach</h4><p>Our first <em>naïve </em>attempt could be to execute everything in a single job. Our relevant configuration (a little bit simplified) for this would look like <a href="https://gist.github.com/rogererill/bdbf885099ae9d94b0853a153cf9eab9">this one</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*GSAWwHk2lSTgbO-NC2Anlg.png" /><figcaption>Not very interesting, uh? Zero parallelism</figcaption></figure><p>Using this, we don’t benefit at all from parallelism, and the average time for our pipeline is <strong>around 9:15 minutes</strong> with a standard deviation of 43 seconds. This time is pretty much the same we had using Jenkins, where there wasn’t any parallelism either.</p><h4>2. Start splitting things</h4><p>The first suspicious task, and the first to go away is <strong>Download dependencies</strong>. This has not much to do with our own code, but is rather a task made to populate our cache with our gradle dependencies between workflows, so it’s like a favor we’re doing to ourselves to our next build. To download dependencies, we need the source code first, and so do other tasks. So we need to extract that code download it to a new job.</p><p>When you extract a step into a new job, it’s important to <strong>ask yourself what environment do you need</strong> to perform that job. In the case of checkout, we don’t need a machine with Android installed that takes a lot of time to boot! We can use the minimal image we can get with <em>git</em> installed, and that’s <a href="https://gist.github.com/rogererill/8240d28fa5bccfa2b762a9a15f371c82">what we do</a> when we use alpine/git</p><p>For our codebase, downloading the dependencies takes between 20 and 30 seconds, but we’re adding an overhead in the checkout job of around ~5 seconds to spin up the environment and around ~6 seconds to attach and restore the workspace. So our net gain with this movement is around 10 to 20 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*QdlH7DZRgIONhUmhNB4msQ.png" /><figcaption>Our first baby step 👶 towards parallelizing</figcaption></figure><p>If you take a closer look at the picture above, you’ll see that our <strong>pipeline time </strong>is 9:09 but <strong>total computation time </strong>is 9:53, and we can’t lose focus on this number too much because at the end, you also <a href="https://circleci.com/pricing/usage/">pay per minute used</a> (around 0,01$, depending on the instance). When we parallelize, we inevitably have to compute more and you’ll have to decide when the tradeoffs of an added cost vs reduced pipeline time are worth it. For now, let’s move on onto optimizing more our pipeline time.</p><h4>3. Gimme more parallelization</h4><p>Ok, so let’s now focus in our <strong>Static analysis</strong> task. This task only requires our source code to be performed, and it doesn’t influence our compile/assemble in any way. So we could do the same as we did with the download dependencies and we can <strong>save like 1 minute </strong>in our pipeline. The only problem here is that this task could end later than our deploy task. That would mean that we could potentially upload a version that fails the static analysis task. For internal development, we’re ok at taking the risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*071LWtk8m1Pfw_5T_Pw-lQ.png" /><figcaption>Notice how Deploy + Static analysis is almost equal to our previous Deploy job, but the pipeline finishes after 7:15</figcaption></figure><p>Next step would be to think that both <strong>Unit tests </strong>and <strong>Assemble</strong> need the code to be <strong>compiled</strong>, and they can both be executed in parallel. So the logical solution would be to do something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*xqp8OmDedWhP2_Ko375vnw.png" /><figcaption>Like before, we could potentially upload a task that has not passed the unit tests</figcaption></figure><p>Here you see that although our critical path <strong>has been reduced</strong> a little bit and we reduced our pipeline time (now it’s 6:56), overall we’re computing much more time (11:35min). Why does that happen? When we compile, we need to <strong>persist the compiled code</strong> (around 275MB in our case) and then the next two steps must attach it when they start. This adds around like 20–40s in compile step and another 20–40s in each of Assemble and Unit test.</p><h4>4. The final step</h4><p>Carrying all the compiled code adds us a lot of time so we’d like to avoid it. If we think backwards, to deploy we only need an apk, and to generate an apk we only need the source code. So if we use a structure like the following one we can get our pipeline completed in <strong>less than five minutes!! 🎊</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*eJQ8XdO6OJy2HAVC5xekOA.png" /><figcaption>Notice that an added benefit here is that with a separate task for deploy, we can control better which are the mandatory steps to allow a deploy. We also created a step to compile Android tests only</figcaption></figure><p>We aim for <strong>Checkout → Generate APK → Deploy</strong>, and all the checks about the validity of the build are done in parallel. This adds redundant computation, since both Assemble and Unit tests will execute some of the same tasks, but the time lost doing it is less than if we had a separate step and persisted the compiled code. If we compare this workflow with the previous one (called semi-optimized here) you can see we <strong>pipeline time is reduced by 41% </strong>and computation time only increases about 4%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*x7kWoNcKEC3DurYIXsO75Q.png" /><figcaption>Comparison between workflows. We improve a lot the pipeline time without adding much cost</figcaption></figure><p>In the initial approach, when we only had one job and the pipeline time equals computation time, we had an average of 555 seconds. But now let’s take a look to another execution of the same workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*_iQV5CGmJenamTqquqPEqQ.png" /><figcaption>Here, the bottleneck is in <strong>Unit tests</strong> step</figcaption></figure><p>As you notice here, the critical path is <strong>Checkout → Unit tests → Deploy</strong>. Why does that happen? Well, Assemble task has a spin up time of 4s but Unit tests has <strong>60s of spin up time</strong>. If it had been cached too, we could have finished the pipeline 54 seconds sooner 😢. So, <strong>let’s talk again about environments.</strong></p><h4>5. Back to the basics</h4><p>If you recall the first topic we discussed, we agreed that the Docker image created by CircleCI was better than ours, because <strong>in average</strong>, it took less time to spin up. That is true, and that’s what we cared most about with our older workflows, but now, we have four tasks of roughly<em> </em>the same length computing in parallel, and the time of the slowest one is the one creating the bottleneck for the Deploy job.</p><p>What does it mean? Well, if we execute one job, the chances that we get CircleCI image cached are around 76%. But what are the chances that <strong>four out of four </strong>jobs get cached? <strong>Just 34%</strong>. When the four images are cached, the slowest time will be ~3 seconds. And if you check our histogram at the beginning of the article, you’ll notice that when we don’t get the cached image, we suffer a longer penalty that with our custom image. In an approximate average, when CircleCI image isn’t cached, <strong>it takes 50 seconds to spin up the image.</strong></p><p>Summarizing, a 1/3 of our workflows will have a slowest spin up of ~3s and 2/3 will get a slowest spin up of ~50s.</p><blockquote>(0.34)*3 + (0.66)*50 = <strong>34,02s of slowest spin up on average</strong></blockquote><p>Our 21 Buttons Docker image has easier calculations. Only 0,16% of the times we’ll have the four images cached, taking 2s to load. All the other times when the image isn’t cached, it takes around 24s to load the image</p><blockquote>(0.0016)*2 + (0,9984)*24 = <strong>23,96s of slowest spin up on average</strong></blockquote><p>In this particular scenario, our custom image wins and it’s the one that should be used. Be aware that this is assuming that <strong>the four </strong>required tasks for deploy take the same time, which is not true, because Assemble task takes usually longer than the other three, so take this analysis with a pinch of salt, but keep this thinking process in mind when choosing your image strategy 😉</p><h4>6. Conclusion</h4><p>We started with a pipeline that took <strong>9 minutes</strong> to execute. With CircleCI, we achieved an average time of <strong>04:37 minutes</strong> to get the same job done 🚀. We had to consider upgrading the default resource class to get more CPU/RAM, and investigating about Docker images, Gradle settings and workflow structure. At the end, the result has been very satisfactory for us 😄, but each project has different needs, and here we presented the <strong>strategies</strong> you need to follow to achieve your best optimized solutions.</p><p>If you have any doubt/feedback, don’t hesitate to comment below 👇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f040873764e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/21buttons-tech/optimizing-your-circleci-pipeline-time-in-android-f040873764e1">Optimizing your CircleCI pipeline time in Android</a> was originally published in <a href="https://medium.com/21buttons-tech">21 Buttons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Lottie in 21 Buttons: our Android experience]]></title>
            <link>https://medium.com/21buttons-tech/using-lottie-in-21-buttons-our-android-experience-d93254b0f77b?source=rss-dbb9e8bb51de------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93254b0f77b</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[21buttons]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[lottie]]></category>
            <dc:creator><![CDATA[Roger Erill]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 14:08:04 GMT</pubDate>
            <atom:updated>2018-10-31T15:59:45.190Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is it recommended as a way to display your animations?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2rxs7uF60Owhvs_t" /></figure><p>We know that in Android, creating beautiful animations can be quite challenging sometimes. We at 21 Buttons have had a lot of struggles with this, until one day we decided to tackle the problem differently. We used <a href="https://medium.com/airbnb-engineering/introducing-lottie-4ff4a0afac0e">Lottie</a> to render this animation and in this post we’ll show why, and what are the pros and cons of this approach.</p><p>If you check <a href="https://engineering.21buttons.com/how-to-generate-videos-using-lottie-in-android-2db6ecceb2a">our last article</a>, you can see what was our objective: <strong>generate dynamic animations and save them as a video so they can be shared elsewhere. </strong>At 21 Buttons, users can upload pictures of their outfit and <em>tag</em> the clothes they wear, thus creating <em>buttons</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*onQatv1VFLQ_Mwy-PcHrUw.png" /><figcaption>Here’s a typical post in 21 Buttons, where each button tags a piece of clothing</figcaption></figure><p>In the app, you can tap each one to get information about the product, but what about if I want to share my whole look, while displaying all the information about my <em>buttons</em>? <strong>Videolook</strong> is the answer. After a post is published, users have the option to share their <em>Videolook, </em>a video that we generate showing an animation with user-generated <em>buttons.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*InSpM90qoeIHr1NlIIBQYQ.gif" /><figcaption>An example of the videolook, where we animate this buttons creating a video</figcaption></figure><h3>Why do we need Lottie anyway?</h3><p>Before, all these animations were created <strong>manually, frame by frame, using java code</strong> 😖. As you can imagine, this had the following drawbacks:</p><ul><li><strong>Time extensive</strong>:<strong> </strong>it took some time to get it working</li><li>Very difficult to <strong>maintain</strong>: the code becomes full of constants and formulas to calculate the positions and movements</li><li>Low <strong>reusability</strong>: the code is highly coupled to this only animation</li><li>Low <strong>quality animation</strong>: creating animations using Java is obviously much worse than creating them using professional tools made for this, like After Effects</li><li><strong>Duplicate work</strong>: Like us, the iOS team had the same problem with this and they had to solve it in a similar way</li></ul><p>At this point, we did a research on how could we solve this issues and here’s when Lottie appeared to us like a great choice. There were other alternatives like <a href="https://github.com/facebookincubator/Keyframes">Facebook Keyframes</a> but we liked more the simplicity, maturity and capabilities of Lottie and it could solve all of the drawbacks stated previously, but we know we had some work to do too.</p><h3>Adjusting Lottie to work with a variable animation</h3><p>First of all, there was some obvious problem with Lottie. <strong>It is meant to render always the same animation. </strong>And in our use case, the animation is <em>always</em> different for each post! We are animating <em>buttons </em>in and out, and each one has a different position, text information and color. Each videolook can have from 1 to 5 tags in it, so you need to take this into account too.</p><p>How did we solve this issue? <strong>Introducing variables in our JSON file. </strong>Our designer generated the animation, and placed the first <em>button </em>at position [100, 100], the second one at [200,200] and so on. The RGB for the first button was something like [1,1,1], the second [2,2,2]… you get the idea. There were some more variables needed but the procedure to generate them was always similar, make the animation generate a fixed number for them.</p><p>After that, we would run a script on this JSON, <strong>replacing </strong>this hardcoded values for <strong>variables </strong>like button1_initial_coordinate_x Here’s some sample on how it would look like:</p><pre>...</pre><pre>&quot;p&quot;: {<br>    &quot;a&quot;: 1,<br>    &quot;ix&quot;: 2,<br>    &quot;k&quot;: [<br>        {<br>            &quot;s&quot;: [<br>                &quot;button1_initial_coordinate_x&quot;,<br>                &quot;button1_initial_coordinate_y&quot;,<br>                0<br>            ],<br>            &quot;e&quot;: [<br>                &quot;button1_initial_coordinate_x&quot;,<br>                &quot;button1_initial_coordinate_y&quot;,<br>                0<br>            ],<br>            &quot;t&quot;: -49,<br>            &quot;i&quot;: {<br>                &quot;y&quot;: 0.833,<br>                &quot;x&quot;: 0.833<br>            },<br>            &quot;o&quot;: {<br>                &quot;y&quot;: 0.167,<br>                &quot;x&quot;: 0.167<br>            },<br>            &quot;n&quot;: &quot;0p833_0p833_0p167_0p167&quot;<br>        },<br>        <br>...</pre><p>Notice something? Yes, this JSON is <strong>quite difficult to understand</strong>. And long. To generate the animation with five buttons, we needed <strong>8322 </strong>lines of JSON, most of them barely understandable. You can get some sort of documentation <a href="https://github.com/airbnb/lottie-web/tree/master/docs/json">here</a> on what each key means, but generally, if you need to work with the JSON file because the animation does not do what in After Effects does (spoiler: THIS DOES HAPPEN), then you will have a <strong>hard time </strong>doing that.</p><p>And that JSON with variables is the one we saved in our project. Once we got the user’s post and the real tag positions, we would do a replacement again and we’d have the final file to feed Lottie with.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afa617db02bbfd111e2594bcf534b6b7/href">https://medium.com/media/afa617db02bbfd111e2594bcf534b6b7/href</a></iframe><p>That’s it! Now we already had our <em>variable</em> animation working as a charm using Lottie. Or did it?</p><h3>Let’s talk about text</h3><p>Here we found one of the unpleasant surprises in Lottie. If you check at the <a href="http://airbnb.io/lottie/supported-features.html">supported features</a>, you’ll see that <strong>text </strong>is one of them. The problem is, <strong>you can’t center the text </strong>in your animation 😩. It’s an open issue yet (<a href="https://github.com/airbnb/lottie-android/issues/388">#388</a> and <a href="https://github.com/airbnb/lottie-android/issues/481">#481</a>). Another text-related issue comes from <strong>multiline </strong>support (<a href="https://github.com/airbnb/lottie-android/issues/401">#401</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*SIyBh8sRfaWn_OcJ4N4OdA.png" /><figcaption>An example on how text looks like in our new videolook. Text can’t be centered anymore</figcaption></figure><p>Keep in mind that text is not yet supported in iOS, so if you plan on creating an animation with dynamic text for your team, beware of this limitations and issues!</p><h4>Other issues faced</h4><p>We had some unwanted issues with a rotating animation, it seemed like the anchor point was wrongly placed by Lottie and we couldn’t make it work. Another problems came from Bézier deformations and mask effects.</p><h3>To sum up…</h3><p>Besides its flaws stated previously, Lottie allowed us to reach our main goal, that was to be able to generate different animations with ease and without messing a lot with the code. Its performance is really good and we think it’s a great choice if you work with simple animations, although if your intention is to make your animation as customized as possible, it can be hard to debug and make certain effects to work. Overall, <strong>we are pleased we switched to Lottie</strong> and look forward on what new exciting features can this library bring in the future 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93254b0f77b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/21buttons-tech/using-lottie-in-21-buttons-our-android-experience-d93254b0f77b">Using Lottie in 21 Buttons: our Android experience</a> was originally published in <a href="https://medium.com/21buttons-tech">21 Buttons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to generate videos using Lottie in Android]]></title>
            <link>https://medium.com/21buttons-tech/how-to-generate-videos-using-lottie-in-android-2db6ecceb2a?source=rss-dbb9e8bb51de------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db6ecceb2a</guid>
            <category><![CDATA[mediacodec]]></category>
            <category><![CDATA[21buttons]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[lottie]]></category>
            <category><![CDATA[videos]]></category>
            <dc:creator><![CDATA[Roger Erill]]></dc:creator>
            <pubDate>Fri, 07 Sep 2018 07:58:59 GMT</pubDate>
            <atom:updated>2019-07-16T18:35:24.391Z</atom:updated>
            <content:encoded><![CDATA[<h4>Our method to transform your animations into quality videos</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4D2g25eRBPX8lFakrpoBA.png" /></figure><blockquote><strong>EDIT: </strong>I created a very small sample project showing in more detail how to record a Lottie animation into a video. You can check it on <a href="https://github.com/rogererill/LottieRecorderTest">Github</a></blockquote><p>Have you ever wanted to export your Android animations to a video format so you can use them elsewhere? At 21 Buttons, we had this in mind, and in this post, we’ll show you how to achieve that using <strong>Lottie</strong>. For those who don’t know it, Lottie is a library that allows you to add animations in your code very easily. In <a href="https://medium.com/airbnb-engineering/introducing-lottie-4ff4a0afac0e">this post</a> you can get a quick view on what it is and how it works. If you want to know the reasons why we chose Lottie and what challenges we faced, stay tuned for our next post where we’ll talk about our overall experience using it</p><p>In our use case, we show the user an animation and we want them to be able to <strong>save </strong>this animation so it can be shared elsewhere. Here’s an example on how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*5jc_t1mkCwKvMALIYzdzYw.gif" /></figure><p>As you can see, we generate a customized animation depending on the information we’ve got on the post, but how do we generate that is a topic for another post 😉. The thing here is, for each post we want the user to be able to generate a video where the background is their post and above that, the Lottie animation. So, let’s dig in in how can we create a video out of all this.</p><h3>How Lottie works internally</h3><p>Here we’ll list some of the main components in the Lottie library and we’ll explain briefly each one:</p><ul><li>LottieAnimationView: this extends AppCompatImageView and if you just want to display a simple animations, this is your way to go. You could place an XML like</li></ul><pre>&lt;com.airbnb.lottie.LottieAnimationView<br>    android:id=&quot;@+id/animation_view&quot;<br>    android:layout_width=&quot;wrap_content&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    app:lottie_fileName=&quot;my_fancy_animation.json&quot;<br>    app:lottie_loop=&quot;true&quot;<br>    app:lottie_autoPlay=&quot;true&quot; /&gt;</pre><p>and you would have a running animation very easily. But if you want to generate video from Lottie, you won’t use this class.</p><ul><li>LottieDrawable: extends Drawable. It is included inside LottieAnimationView but this can be used to show animations too (although it is preferred to use LottieAnimationView when possible since it handles bitmap recycling and asynchronous loading of compositions). This is the class we will focus on to generate a video.</li><li>LottieComposition: we can say this is the <strong>core class </strong>in Lottie. This class is the one that transforms the JSON input into an animation that will be rendered in the LottieDrawable or the LottieAnimationView. With this class we can know certain attributes of our animation like the number of frames, the layers or the images in it.</li></ul><p>Now that we know the main players, let’s see how can we start generating a video from a Lottie animation.</p><h3>How to load an animation</h3><p>The first step is to load our animation. There are multiple ways to feed our composition: via assets file, res/raw file, using an InputStream or simply from a String. For us, it’s irrelevant the way you load your animation into your LottieComposition. Once you have it, you have to set it to a newly created LottieDrawable. Something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9816b6d1df7a69e0db687b80c70e7928/href">https://medium.com/media/9816b6d1df7a69e0db687b80c70e7928/href</a></iframe><p>As you can see, this part it’s pretty easy 😄. Now we’ll move on on what to do with our newly created animation</p><h3>This is where fun starts</h3><p>Our main goal is to generate a video from this animation. The main approach to take is the following:</p><ol><li>Set the animation to a specific frame</li><li>Generate a drawable from that frame</li><li>Send this drawable to the InputSurface of a MediaCodec class</li><li>Send the generated bytes to a MediaMuxer</li></ol><p>And we repeat this over and over until there are no more frames in our animation. Then, we would call make a special call to signal to end the video</p><h4>How can we achieve this?</h4><p>The diagram below schematically shows the classes we have used to be able to generate videos. In blue, we have our created classes, in green, Android classes and in red, Lottie classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*dFL6XakPJkEIayUB34ZxgA.png" /></figure><p>First, we’ll talk about RecordingOperation. This class serves like a kind of <strong>manager </strong>that starts and ends the recording. In a simplified way, the class looks similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93972291cd4f09fc0869ca8eff530335/href">https://medium.com/media/93972291cd4f09fc0869ca8eff530335/href</a></iframe><p>As you can see, we simply need to call the method start() to get things going. In our MVP architecture that we’re following, the <em>presenter</em> is the one communicating with this class.</p><p>Now, we’ll get into the FrameCreator class. As you can guess from its name, this class will get us a Drawable to pass on to the Recorder. It also helps us to know the progress of our recording. This class is quite simple, and gets to be something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4038a2fc1a664fe0081d117361f1ae84/href">https://medium.com/media/4038a2fc1a664fe0081d117361f1ae84/href</a></iframe><p>First of all we should scale manually our Lottie animation so it fits the video correctly. The constant VIDEO_WIDTH_PX sets the resolution of the video, and it needs to have the same value in our Recorder class.</p><p>The generateFrame() method is deceptively simple. It took us some time experimenting with other solutions until we found this one that simply works as a charm. You can set your lottie animation to any frame you want, you increment the frame index and after that you return the lottieDrawable itself. This works like sending a ‘screenshot’ of that particular frame</p><h3>Getting to the recording</h3><p>It’s been easy so far, right? 😄 Now we’ll dig into the more mysterious part, the Recorder. This class is full of Android media-related classes, most of them calling native methods which there is no documentation for, and when they crash, it’s really cryptic and difficult to know what happened (the ones like <em>Fatal signal (SIGSEV) code 1</em> 😢).</p><p>We basically followed this code used in <a href="https://github.com/google/grafika/blob/master/app/src/main/java/com/android/grafika/SoftInputSurfaceActivity.java"><strong>Grafika</strong></a>, with some minor tweaks. First we set the MediaFormat with parameters like bitrate, framerate, etc. Then we create the MediaEncoder that will allow us to get a Surface, the place where we’ll work with our frames. Finally, we create the MediaMuxer.</p><p>Now we have added our method nextFrame(currentFrame: Drawable) that will add our frame to the video. We also have the method end() to signal that there will be no more frames. This two methods are the ones called from RecordingOperation. The code for it is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a8407280d3e9dcfa2e6b4614c4a4b0/href">https://medium.com/media/91a8407280d3e9dcfa2e6b4614c4a4b0/href</a></iframe><p>Using the lock/unlock methods in the surfaces is how we post content into them, and this information will get into the video at the next frame when we call drainEncoder method.</p><p>And that’s it! 🎉 🎊 Basically with this you can have your cool .mp4 video of a Lottie Animation. But of course, it wasn’t so easy for us 😅. Here are some issues and challenges we found along the way.</p><h3>The performance issues</h3><p>We had some struggles until we found the perfect solution for us in terms of performance. The first (obvious) thing is: <strong>you shouldn’t do any of this on the main thread. </strong>This recording operations are really heavy and will take some time. For your reference, an animation of about 10 seconds takes us <strong>between 9 and 13 seconds to process into a video</strong>. It depends a lot on the animation’s complexity and frame rate, and also the computing power of the device. Important note here: <strong>our videos contain music. </strong>This is not covered in this tutorial but basically means adding more code only to the Recorder class. So that obviously will add some time in the process of video generation.</p><p>At first, we wanted the user to be able to see the animation <em>at the same time it was being recorded</em>. It turns out that this is not a good solution since at the eyes of the user, the animation <strong>lagged a lot</strong>. It also hurt the video generation time, although not much. So we decided to have <strong>two animations at the same time. </strong>One is simply a LottieAnimationView defined in the Activity that was called <strong>playingAnimation</strong>. Here we would load the animation in a simple way and play it in loop in our Main Thread, so the user experience is really good.</p><p>Then we had a LottieDrawable called <strong>recordingAnimation</strong> that <strong>was never visible to the user 👻. </strong>And this one is the LottieDrawable instance we load programmatically as shown in the section above and passed on to the FrameCreator class. Actually, this animation <strong>is never “played”</strong>, since we only keep setting a single frame and taking a snapshot of the animation at that point. All of this happens in a <strong>background thread</strong> so the UI is being responsive the whole time.</p><p>At the end, we couldn’t show the user the same animation we where recording because with some animations (the more complex ones) the video recorder crashed if we were displaying an animation at the same time. The crash was:</p><blockquote>Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid</blockquote><p>This was quite a random crash and there was not much we could do 🤷. So we decided to show the user a lighter and smaller loading animation while the video was being generated.</p><h3>Other issues faced</h3><p>One surprise we got was that the <strong>text in our animations wasn’t displayed in the video 😰. </strong>The problem was with the <strong>recordingAnimation</strong> we talked about before. As this animation was not visible to the user, it was never placed into a XML file or attached to a LottieAnimationView. And because of that, the class FontAssetManager inside the LottieDrawable didn’t have any Context and could not load the project assets to get the font. The issue is referenced here (<a href="https://github.com/airbnb/lottie-android/issues/726">#726</a>) and the solution for that is basically to attach <strong>any View</strong> to the LottieDrawable. So we need to have a weird code in our Activity that is like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/378d51c23a67ca85a8f16288c1cbfa93/href">https://medium.com/media/378d51c23a67ca85a8f16288c1cbfa93/href</a></iframe><p>Our Activity’s <em>presenter</em> is the one who generated the recordingLottieDrawable and loads it with a LottieComposition, but then it is forced to send it to the <em>view </em>to attach it an empty view and return it back to the <em>presenter </em>so the recording can start.</p><p>Other issues are not related to the recording process and will be in our article explaining our overall experience in Lottie.</p><p>Thanks for reading this post and… Happy recording 📹 🎥 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db6ecceb2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/21buttons-tech/how-to-generate-videos-using-lottie-in-android-2db6ecceb2a">How to generate videos using Lottie in Android</a> was originally published in <a href="https://medium.com/21buttons-tech">21 Buttons Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>