<?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 Saurabh Arora on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Arora on Medium]]></description>
        <link>https://medium.com/@saurabharora90?source=rss-cf7384765f9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LMmzIRgIbylPO-2-tQ9L3g.jpeg</url>
            <title>Stories by Saurabh Arora on Medium</title>
            <link>https://medium.com/@saurabharora90?source=rss-cf7384765f9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:18:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saurabharora90/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[Building a Speedometer with Compose Canvas API]]></title>
            <link>https://medium.com/google-developer-experts/building-a-speedometer-with-compose-canvas-api-acefb35dc12e?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/acefb35dc12e</guid>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[compose-ui]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Mon, 23 Oct 2023 06:21:13 GMT</pubDate>
            <atom:updated>2023-10-26T18:53:34.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*RYOU0zj_gkuTd2l6ZDS6hA.png" /></figure><p>The other day, while sitting in the back of a taxi, I noticed the speedometer and had the idea to build one using Jetpack Compose (because, why not? 😛). In this post, I will explain the process of building the speedometer and discuss the challenges I faced. This post assumes a basic knowledge of the Canvas API in Jetpack Compose.</p><p>The speedometer we are building will look like the one above.</p><h3>The Canvas and Drawing the Arc</h3><p>To bring our vision of the speedometer to life, we leverage the powerful Canvas API in Jetpack Compose. This API empowers us to create, manipulate, and render shapes, lines, and text directly onto the screen, endowing us with precise control over the speedometer’s visual representation.</p><p>Once we have access to the Canvas, we will use the drawArc function to draw the semicircular arc that represents the speed range. This function requires several parameters, including the start angle and sweep angle, both measured in degrees. In our speedometer, we set the start angle to 30 degrees, which corresponds to the starting point of the speedometer arc.</p><blockquote><em>For </em><em>drawArc, It starts from </em><em>startAngle degrees (with zero degrees being 3 o’clock), drawing up clockwise to the </em><em>sweepAngle relative to the startAngle.</em></blockquote><p>For the sweep angle, we opt for -240 degrees. A negative value in this context signifies a counterclockwise sweep. This choice produces a semicircular arc spanning from 30 degrees to 270 degrees, encompassing a 240-degree arc, thereby crafting the characteristic shape of the speedometer.</p><pre>val modifier = Modifier.padding(90.dp).requiredSize(360.dp)<br>Canvas(modifier = modifier, onDraw = {<br>    // Draw the speedometer arc<br>  drawArc(<br>      color = Color.Red,<br>      startAngle = 30f,<br>      sweepAngle = -240f,<br>      useCenter = false,<br>      style = Stroke(width = 2.0.dp.toPx())<br>  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*X5x-6RF7zjTn5ROXu6ohgg.png" /></figure><h3>Drawing the SpeedMarkers</h3><p>The markers are divided into three types: major, minor, and small indicators. Major indicators represent significant speed intervals (multiples of 20) and are drawn using a thick line to emphasise their importance. Minor indicators represent intermediate speed intervals (multiples of 10) and are drawn using a medium-sized line. Small indicators are used to fill in the gaps between major and minor indicators (multiples of 2) and are drawn with a thin line.</p><h4>The Mathematics Behind Marker Placement</h4><p>To draw the marker line using the drawLine method, we need to provide a startPoint and an endPoint. In order to determine the startPoint on the arc (i.e., where the line starts), we can use trigonometry (remember middle school math?). Here&#39;s how we can calculate the point on a circle:</p><ol><li>Determine the angle at which we want to place the point on the circle. This angle is measured in degrees.</li><li>Use the following function to calculate the coordinates of the point:</li></ol><pre>private fun pointOnCircle(<br>     thetaInDegrees: Double,<br>     radius: Float,<br>     cX: Float,<br>     cY: Float,<br> ): Offset {<br>     val x = cX + (radius * sin(Math.toRadians(thetaInDegrees)).toFloat())<br>     val y = cY + (radius * cos(Math.toRadians(thetaInDegrees)).toFloat())<br>    <br>     return Offset(x, y)<br> }</pre><ul><li>x and y are the coordinates of the point on the circle.</li><li>cX and cY are the coordinates of the centre of the circle.</li><li>radius is the radius of the circle.</li><li>The angle is converted to radians using the formula: thetaInRadians = Math.toRadians(thetaInDegrees)</li></ul><p>Similarly, we can calculate the endPoint by adjusting the radius of the circle based on the length of the marker we are drawing. Finally, we can connect the startPoint and endPoint using the drawLine method to draw the marker line.</p><h4>Marker</h4><p>To draw the markers, we start counting down from 300 to 0 in steps of 2, following the small indicator as defined above. Each of the marker indicators is then drawn.</p><p>Here is the relevant code snippet (note the use of INDICATOR_INITIAL_OFFSET to create a small gap between the arc and the marker start point, as shown in the screenshot below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mofupq53UtiIblIZqeLrzw.png" /></figure><pre>for (angle in 300 downTo 60 step 2) {<br>    val speed = 300 - angle<br><br>val startOffset = pointOnCircle(<br>        thetaInDegrees = angle.toDouble(),<br>        // Offset from the center to start drawing the markers<br>        radius = size.height / 2 - INDICATOR_INITIAL_OFFSET.dp.toPx(),<br>        cX = center.x,<br>        cY = center.y<br>    )<br>    if (speed % 20 == 0) {<br>        // Major indicator marker<br>        val endOffset = pointOnCircle(<br>            thetaInDegrees = angle.toDouble(),<br>            // Length of major indicator<br>            radius = size.height / 2 - MAJOR_INDICATOR_LENGTH.toPx(),<br>            cX = center.x,<br>            cY = center.y<br>        )<br>        // Draw the major indicator marker using a thick line<br>        speedMarker(startOffset, endOffset, SolidColor(Color.Black), 4.dp.toPx())<br>    } else if (speed % 10 == 0) {<br>        // Minor indicator marker<br>        val endOffset = pointOnCircle(<br>            thetaInDegrees = angle.toDouble(),<br>            // Length of minor indicator<br>            radius = size.height / 2 - INDICATOR_LENGTH.toPx(),<br>            cX = center.x,<br>            cY = center.y<br>        )<br>        // Draw the minor indicator marker using a medium-sized line<br>        speedMarker(startOffset, endOffset, SolidColor(Color.Blue), 2.dp.toPx())<br>    } else {<br>        // Small indicator marker<br>        val endOffset = pointOnCircle(<br>            thetaInDegrees = angle.toDouble(),<br>            // Length of small indicator<br>            radius = size.height / 2 - INDICATOR_LENGTH.toPx(),<br>            cX = center.x,<br>            cY = center.y<br>        )<br>        // Draw the small indicator marker using a thin line<br>        speedMarker(startOffset, endOffset, SolidColor(Color.Blue), 1.dp.toPx())<br>    }<br>}<br>private fun DrawScope.speedMarker(<br>    startPoint: Offset,<br>    endPoint: Offset,<br>    brush: Brush,<br>    strokeWidth: Float<br>) {<br>    drawLine(brush = brush, start = startPoint, <br>    end = endPoint, strokeWidth = strokeWidth)<br>}</pre><p>Notably, there’s an apparent disparity between the start and sweep angles when drawing the arc (30 and -240 degrees) and the angles used for marking and speed representation (300 to 60 degrees).</p><p>In the <strong>drawArc</strong> function, the start angle is determined by measuring the angle from the centre of the circle to the intersection point with the 3 o&#39;clock position. However, when we come to placing the markers on the speedometer, we consider the entire circular context to which the speedometer arc belongs. In this context, the arc begins at 300 degrees and ends at 60 degrees, where 300 degrees corresponds to 0 speed and 60 degrees signifies the maximum speed (in this case, 240).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mXSJSyFqqfgn2RuhhPu8XQ.png" /></figure><h3>Drawing the speed text</h3><p>Each major indicator on the speedometer is associated with a speed value. To display the speed text uniformly along the arc, we will again use the pointOnCircle method again to determine the starting point for the text.</p><pre>val textOffset = pointOnCircle(<br>        thetaInDegrees = textAngle,<br>        radius = size.height / 2 - MAJOR_INDICATOR_LENGTH.toPx()<br> - INDICATOR_INITIAL_OFFSET.toPx(),<br>        cX = center.x,<br>        cY = center.y<br>    )<br><br>drawContext.canvas.save()<br>drawContext.canvas.translate(<br>    textOffset.x,<br>    textOffset.y<br>)<br>// Draw the speed text at the calculated position and angle<br>drawText(textLayoutResult)<br>drawContext.canvas.restore()</pre><p>Now that we have calculated the position of the speed text, we can proceed to draw it on the canvas. Before applying any transformations (such as translations or rotations), we save the current state of the canvas using the drawContext.canvas.save() function. This ensures that we can restore the canvas to its original state after drawing the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*vxgJerKhsvpB30B_B5MT4Q.png" /></figure><p>Here, the text is not properly aligned with the markers, and the spacing between the marker and text is inconsistent across the speedometer. This is because the point on the circle is being calculated based on the start of the text. Instead, we should use the centre of the text’s width as the reference point. The width of the text changes based on the speed, whether it is single-digit, double-digit, or triple-digit. To address this, we can use the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/text/TextMeasurer">TextMeasurer</a> to obtain the width of the text and factor it into our calculation.</p><pre>val textLayoutResult = textMeasurer.measure(speed.toString())<br>val textWidth = textLayoutResult.width<br>val textHeight = textLayoutResult.size.height<br>val textOffset = pointOnCircle(<br>        thetaInDegrees = textAngle,<br>        // Adjusting radius with text width<br>        radius = size.height / 2 - MAJOR_INDICATOR_LENGTH.toPx() <br>        - textWidth / 2 - INDICATOR_INITIAL_OFFSET.toPx(),<br>        cX = center.x,<br>        cY = center.y<br>    )<br>//draw the text as above<br>drawContext.canvas.save()<br>drawContext.canvas.translate(<br>    textOffset.x - textWidth / 2,<br>    textOffset.y - textHeight / 2<br>)<br>// Draw the speed text at the calculated position and angle<br>drawText(textLayoutResult)<br>drawContext.canvas.restore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*C-Bhi2U8GedoYTg7LobJ7A.png" /></figure><p>Looks much better now :)</p><h3>Drawing the Speed Indicator</h3><p>The only thing left now is the speed indicator. Similar to the speed markers, the indicator is a simple line. Its starting point is the centre of the arc, and its ending point is determined by the current speed’s position on the arc. We can use the pointOnCircle method to obtain the starting and ending points for the indicator.</p><pre>private fun DrawScope.speedIndicator(<br>    speedAngle: Float<br>) {<br>    val endOffset = pointOnCircle(<br>        thetaInDegrees = speedAngle.toDouble(),<br>        radius = size.height / 2 - INDICATOR_LENGTH.toPx(),<br>        cX = center.x,<br>        cY = center.y<br>    )<br><br>    drawLine(<br>        color = Color.Magenta,<br>        start = center,<br>        end = endOffset,<br>        strokeWidth = 6.dp.toPx(),<br>        cap = StrokeCap.Round,<br>        alpha = 0.5f<br>    )<br>}</pre><p>That’s it. We now have our speedometer.</p><blockquote><em>We can also accept the speed value as a user input to animate the indicator and bring our speedometer to life:</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//twitter.com/iSaurabhArora/status/1683161546896310273%3Fs%3D20&amp;image=https%3A//i.embed.ly/1/image%3Furl%3Dhttps%253A%252F%252Fabs.twimg.com%252Ferrors%252Flogo46x38.png%26key%3Da19fcc184b9711e1b4764040d3dc5c07" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/4586c06ebb83ee065f9e4035387a7879/href">https://medium.com/media/4586c06ebb83ee065f9e4035387a7879/href</a></iframe><p>The full code for this (along with animation and seek bar for demo) can be found at: <a href="https://gist.github.com/saurabharora90/636ca81907e20997199795ca16368276">https://gist.github.com/saurabharora90/636ca81907e20997199795ca16368276</a></p><p><em>This post originally appeared on </em><a href="https://saurabharora.dev/posts/building-a-speedometer-with-compose-canvas-api/"><em>saurabharora.dev</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acefb35dc12e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-developer-experts/building-a-speedometer-with-compose-canvas-api-acefb35dc12e">Building a Speedometer with Compose Canvas API</a> was originally published in <a href="https://medium.com/google-developer-experts">Google Developer Experts</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proguard/R8 in the world of modularity]]></title>
            <link>https://medium.com/android-news/proguard-r8-in-the-world-of-modularity-f599650b4553?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f599650b4553</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[proguard]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 07:25:48 GMT</pubDate>
            <atom:updated>2020-01-16T07:57:43.274Z</atom:updated>
            <content:encoded><![CDATA[<p>The benefits of modularing our apps have been echoed a lot in the community and by Google itself. Here I would like to discuss how we should look into handling Proguard/R8 rules files in this new world.</p><p>Generally, developers tend to maintain their Proguard rules file in their application module. This is mostly okay if the modules are only consumed by one application. But what if those modules are shared across multiple apps? Like at Viki, where most of our modules have code that is used in both TV and mobile apps. With shared modules across apps, changes in our module code and missing Proguard configuration would sometimes break our release builds for both mobile and TV apps. Initially, we would add the missing proguard rules to both the apps but eventually, we felt it might serve us better to have the proguard rules in the module directly.</p><p>By including the proguard rules in the modules directly, the consuming apps don’t need to worry about updating their rules because a module that they include has changed its internal dependencies or structures.</p><p><strong>### Consumer Proguard Files</strong></p><p>If we use Android Studio to create a new module (Android Library), then the build.gradle file that is generated for the new module contains a consumerProguardFiles ‘consumer-rules.pro&#39; section under defaultConfig. In case you already have an existing module, you can add a section for the consumerProguardFiles as follows:</p><pre>defaultConfig {</pre><pre>      minSdkVersion 21</pre><pre>      targetSdkVersion 29</pre><pre>      .....</pre><pre>      consumerProguardFiles ‘consumer-rules.pro’</pre><pre>}</pre><p>A consumer proguard rules file is like any other proguard rules files with the caveat that the rules inside it are automatically applied to the consuming application when the application is being built in a proguard enabled mode. This file is not used for immediate minification (i.e. when building the library itself). It is only used when the consumer of the library is being built. We should anyways not be minifying the module when it is being built, because, at that point, the module doesn’t know what parts of it are being consumed. It is for this reason that the default build.gradle that is generated for a library module has minifyEnabled as false</p><pre>buildTypes {</pre><pre>        release {</pre><pre>             minifyEnabled false</pre><pre>             proguardFiles getDefaultProguardFile(‘proguard-android-               optimize.txt’), ‘proguard-rules.pro’</pre><pre>          }</pre><pre>  }</pre><p><strong>### Adding Rules</strong></p><p>To bundle proguard rules with your module, add the rules to the consumer-rules.pro file. At Viki, we have a module that houses all our playback logic (including ads) and we always add the ad provider’s Proguard rules in the modules consumer proguard files to allow the rules to available to both our TV and Mobile apps.</p><pre>-keep class com.google.ads.interactivemedia.** { *; }</pre><pre>-keep interface com.google.ads.interactivemedia.** { *; }</pre><pre>-keep class com.google.obf.** { *; }</pre><pre>-keep interface com.google.obf.** { *; }</pre><p>P.S — The above rules are just an example and might not be the best for your use case.</p><p><strong>**Note**</strong> — You don’t need to name the file as consumer-rules.pro. You can name it anything. We only need to make sure that we point to the correct file under the build.gradle consumerProguardFiles attribute.</p><p><strong>## TLDR</strong></p><p>Consumer proguard rules have been actively used by third-party libraries and that is how they bundle proguard rules in their AAR. In this new bold world of modularity, every module included in your app can be treated as a third party library and hence can/should house it’s own Proguard/R8 rules.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f599650b4553" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/proguard-r8-in-the-world-of-modularity-f599650b4553">Proguard/R8 in the world of modularity</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Android Lint Theme Aware — Part 2]]></title>
            <link>https://proandroiddev.com/making-android-lint-theme-aware-part-2-92cd5e6c7c9e?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/92cd5e6c7c9e</guid>
            <category><![CDATA[lint]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dark-theme]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Tue, 06 Aug 2019 15:20:19 GMT</pubDate>
            <atom:updated>2019-08-07T05:50:32.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Android Lint Theme Aware — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR0C_Cn5IUzyiWVRfvA-tg.png" /><figcaption>When Android Lint meets Dark Theme</figcaption></figure><p>Over the last year or so, we have seen a lot of apps provide support for Dark Theme in their apps. Android Q brought this toggle to the system setting. Eventually, users will expect all apps to have/provide support for Dark theme and apps not doing so will be the exception rather than the norm.</p><p>Through these series of posts, we’ll see how we can use Android Lint to help us build and eventually maintain an app that supports a day and night theme variant.</p><p>You can read Part 1 here:</p><p><a href="https://proandroiddev.com/making-android-lint-theme-aware-6285737b13bc">Making Android Lint Theme Aware</a></p><p>In Part 1, we saw how we can write a lint check that will flag layouts and drawables files which have hardcoded hex color values (#FFFFFF) and help in migrating them to use color resources (@color/white) instead.</p><p>In this post (Part 2), we’ll see how we can detect color resources that don’t have a corresponding dark theme (night qualifier) variants.</p><p>First up, let’s define the lint issue describing the problem we are looking for in our source code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e3e32c7f37e43f1c263ddb3ca31f02/href">https://medium.com/media/88e3e32c7f37e43f1c263ddb3ca31f02/href</a></iframe><p>The issue is self-explanatory, so let’s look at the detector class (MissingNightColorDetector) that we have already bonded this issue with.</p><p>In Android, colors resources are defined under the values folder in a colors.xml file. Since we are looking for issues inside XML files, we’ll use the ResourceXmlDetector which defines how an XML file is parsed. It might help to understand the XML markup before proceeding. You can read about it <a href="https://www.w3schools.com/xml/">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d6adf9c94f61b02dfe9911f91a4b67c/href">https://medium.com/media/1d6adf9c94f61b02dfe9911f91a4b67c/href</a></iframe><p>In <a href="https://proandroiddev.com/making-android-lint-theme-aware-6285737b13bc">Part 1</a>, when we were looking for hardcoded colors, we looked at <a href="https://www.w3schools.com/xml/xml_attributes.asp">XML attributes</a>. For parsing the colors.xml file (located inside the values folder), we need to look at <a href="https://www.w3schools.com/xml/xml_elements.asp">XML Elements</a>. We simply can’t declare support for the name attribute as that will also match other resources like String Resources, Style Resources, etc. Hence we declare support for the “color” element (see: getApplicableElements) and then look at the name attribute inside the “color” element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d3d748e5454331e4e8601f888a7343/href">https://medium.com/media/f0d3d748e5454331e4e8601f888a7343/href</a></iframe><p>visitElement is then called for each XML element that the detector has mentioned it wants to analyze. Here, we extract out the color name (and NOT its value) and store it in a list representing the configuration of the values folder (regular/night). Finally when project inspection is complete (afterCheckEachProject), we report an issue for every color that exists in the regular value folder but not in the night variant folder.</p><p>Finally, update the registry to include the new check:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d48a07e6104911bf8daa5fc1dbc7812/href">https://medium.com/media/7d48a07e6104911bf8daa5fc1dbc7812/href</a></iframe><p>Run the lint check as usual and we should see new lint errors appear in the project (if there are missing night variant color resources).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ed_GQK6avi8gCrf8o8KNow.png" /><figcaption>Colors with a missing night variant flagged</figcaption></figure><p>That&#39;s it! With both the lint checks in place, warnings will be raised if we ever use a hardcoded hex color in our layout/drawables app and if we add a color resource but forget to add a corresponding night variant for it. By integrating lint checks with the CI system, these are a few less thing us developers need to worry about in code reviews/PRs.</p><p>The above code has been converted to a lint checks library for developers to easily integrate with their apps. Check it out at <a href="https://github.com/saurabharora90/Lint-Checks">https://github.com/saurabharora90/Lint-Checks</a>.</p><p><strong>Remember to appreciate (clap) the post if you learned something or it was helpful.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92cd5e6c7c9e" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/making-android-lint-theme-aware-part-2-92cd5e6c7c9e">Making Android Lint Theme Aware — Part 2</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[Making Android Lint Theme Aware]]></title>
            <link>https://proandroiddev.com/making-android-lint-theme-aware-6285737b13bc?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6285737b13bc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[dark-theme]]></category>
            <category><![CDATA[lint]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Mon, 29 Jul 2019 18:18:54 GMT</pubDate>
            <atom:updated>2020-02-20T16:28:06.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Android Lint Theme Aware — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LR0C_Cn5IUzyiWVRfvA-tg.png" /></figure><p>Over the last year or so, we have seen a lot of apps provide support for Dark Theme in their apps. Android Q brought this toggle to the system setting. Eventually, users will expect all apps to have/provide support for Dark theme and apps not doing so will be the exception rather than the norm.</p><p>In this post, I am not going to talk about how we can add dark theme support to our apps. For that we can consult my other post:</p><p><a href="https://android.jlelse.eu/preparing-your-app-for-android-q-199e0f8edfc6">Preparing your app for Android Q</a></p><p>Through these series of posts, we’ll see how we can use Android Lint to quickly detect screens in our app which aren’t yet ready to support a dark theme variant. Using lint will also make our implementation future proof, as it will complain when a color is hardcoded in a layout/vector drawable file (used as #FFFFFF instead of @color/white) or a color resource has been added but it doesn’t contain a dark theme (night qualifier) variant.</p><p>Android lint system provides a lot of helpful checks but it’s not exhaustive. It’s difficult to build all checks as they can vary as per user needs. Hence, Lint provides an API, to allow users to build their own checks. We’ll use this powerful capability to build two types of checks to help us with building and maintaining dark-theme:</p><ul><li>Warn about hardcoded colors. If we want to add support for a dark theme in our apps, hardcoded colors in XML files (especially layout files), are a big no. (Part 1)</li><li>Warn about missing color resources in dark theme (night qualifier) variants. (<a href="https://proandroiddev.com/making-android-lint-theme-aware-part-2-92cd5e6c7c9e">Part 2</a>)</li></ul><h3>Brief Overview of Lint</h3><p>A lint check is made up of four basic entities:</p><ol><li><strong>Issue</strong>: An issue is a problem in the source code. This is what comes up in the lint report files.</li><li><strong>Detector</strong>: A class which is used to detect issues/problems in the source code. Essentially this where the issue (problem) detection logic resides. A detector can report multiple issues.</li><li><strong>Implementation</strong>: Binds an issue with a detector class so that lint know where to look for a given issue.</li><li><strong>Registry</strong>: A list of all the list of checks to be performed on an Android project</li></ol><p>Not let’s look at how we can detect hardcoded colors in our XML files. First, let’s set up a Java Library module which will house our lint checks and add a dependency to the lint API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1852669737e2a3fbe9859edce91d7bc7/href">https://medium.com/media/1852669737e2a3fbe9859edce91d7bc7/href</a></iframe><h3>Issue</h3><p>Next up, let’s define the issue that we are going to look for in the source code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad8d2012fce2612434fc1257526656c6/href">https://medium.com/media/ad8d2012fce2612434fc1257526656c6/href</a></iframe><p>An issue is made up of:</p><ul><li><strong>Id</strong> — the fixed id of the issue</li><li><strong>Description</strong> — A short summary describing the problem rather than the fix</li><li><strong>Explanation</strong> — a full explanation of the issue, with suggestions for how to fix it</li><li><strong>Category</strong> — the associated category, if any</li><li><strong>Priority</strong> — the priority, a number from 1 to 10</li><li><strong>Severity</strong> — the default severity of the issue</li><li><strong>Implementation</strong> — the default implementation for this issue. We have already bonded this issue with a detector class.</li></ul><h3>Detector</h3><p>Android Lint provides various detectors for us to use depending on the type of file we want to scan. Since we are looking for issues inside XML files, we’ll use the ResourceXmlDetector which defines how an XML file is parsed. It might help to understand the XML markup before proceeding. You can read about it <a href="https://www.w3schools.com/xml/">here</a></p><p>Next, let’s define the attributes (such as background, foreground, textColor, tint, fillColor, etc) where we could have hardcoded colors directly instead of referencing them. Hardcoded colors are a big no when it comes to adding support for a dark theme. These will be the list of <a href="https://www.w3schools.com/xml/xml_attributes.asp">attributes</a> that our detector declares that it wants to analyze.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a1197679bdac832c4e5271c3805c39d/href">https://medium.com/media/4a1197679bdac832c4e5271c3805c39d/href</a></iframe><p>visitAttribute is then called for each attribute that the detector has mentioned it wants to analyze. Here we check if the value of the attribute begins with a # (such as #FFFFFF) and if it does, we report it as an issue that we had defined earlier. context.getLocation<em>(</em>attribute<em>) </em>gets the exact line number of the issue so that it can be pointed out the in HTML/XML report file that is generated at the end.</p><p>Note: The example above goes through all XML files (layouts, drawables, vector assets, etc.)</p><h3>Registry</h3><p>Finally, we will create a Registry of our lint checks and update the build.gradle so that Lint can pick it up when it runs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0451eb6c63ad31da51ce3e6f3963a535/href">https://medium.com/media/0451eb6c63ad31da51ce3e6f3963a535/href</a></iframe><h3>Usage</h3><p>To incorporate this newly created lint check in your app, update your app’s build.gradle file to include a dependency to the lint module:</p><pre>dependencies {</pre><pre>....<br>lintChecks project<em>(</em>&#39;:dark-theme-lint&#39;<em>)<br></em>}</pre><p>Run the lint check as usual and you should see new lint errors appear in your project (if you have any hardcoded colors in your XML files)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L7QDh1oQhOfxwBslVU2Tag.png" /><figcaption>Direct Color Use Lint Check on a sample project</figcaption></figure><p>Now we have a comprehensive list of places where a color value has been hardcoded. Once we have resolved these warnings by using color resources, this lint check will act as a deterrent for future developers being able to hardcode color values in layout/drawable files. By integrating lint checks with the CI system, this is one less thing us developers need to worry about in code reviews/PRs.</p><p>In part 2, we will add another lint check that will warn about color resources that don’t have a corresponding dark theme (night qualifier) variants. Follow me on <a href="https://twitter.com/saurabh_arora90">Twitter</a> or Medium to be notified when the next post is available. I’ll also update this post with a link to the next article.</p><p>Update: Read Part 2 Here:</p><p><a href="https://medium.com/@saurabharora90/making-android-lint-theme-aware-part-2-92cd5e6c7c9e">Making Android Lint Theme Aware — Part 2</a></p><p><strong>Remember to appreciate (clap) the post if you learned something or it was helpful.</strong> The custom lint checks are available as a library for integration with your apps. More details on Github: <a href="https://github.com/saurabharora90/Lint-Checks">https://github.com/saurabharora90/Lint-Checks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6285737b13bc" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/making-android-lint-theme-aware-6285737b13bc">Making Android Lint Theme Aware</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[Preparing your app for Android Q]]></title>
            <link>https://medium.com/android-news/preparing-your-app-for-android-q-199e0f8edfc6?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/199e0f8edfc6</guid>
            <category><![CDATA[android-q]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Thu, 11 Jul 2019 15:53:54 GMT</pubDate>
            <atom:updated>2019-08-02T14:48:50.554Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*1sGwBapb_gbatTKnQ7RTzQ.png" /></figure><p>We are into the 10th year of Android development (Android Q should be 10.0). As per Beta 4, Android Q is officially <a href="https://android-developers.googleblog.com/2019/06/android-q-beta-4-and-final-apis.html">API level 29</a>. Even though we have a <a href="https://android-developers.googleblog.com/2019/07/android-q-beta-5-update.html?linkId=70315877">Beta 5</a> and a Beta 6 is expected, the API’s have been marked as final and now is a good time to see how Android Q will affect your app and what changes should be made to fully support Android Q.</p><p>The important changes (and not the full list) introduced in Android Q can be divided into two categories: a) Privacy &amp; Security. b) User Experience</p><h3>1) Privacy &amp; Security</h3><h4>a) Background Activity Starts</h4><p>If you try to start an activity, while your app is in the background, it will no longer be allowed.</p><ul><li><strong>Affects:</strong> All apps running on Q (irrespective of target SDK). An exception is thrown if the app targets Android Q while the activity just doesn’t launch if the app doesn’t target Android Q but is running on an Android Q device.</li><li><strong>Exceptions:</strong> Bound services such as accessibility, auto-fill, etc. If the app receives a PendingIntent from the system, we use can use it to launch an activity. If the app has SYSTEM_ALERT_WINDOW permission (removed in the Android GO edition) or the app called finish() on an activity very recently (would not recommend relying on this. The idea of “recently” can be very dubious), then your app is exempted from this restriction as well.</li><li><strong>Recommended approach: </strong>Notification Triggered activity</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a9ea0d2d57b86f67d77db29e0983c3/href">https://medium.com/media/40a9ea0d2d57b86f67d77db29e0983c3/href</a></iframe><p>So if we want to launch an activity from the background, first create a Notification to display to the user. In that notification, add a Fullscreen pending intent. Also, add the USE_FULL_SCREEN_INTENT permission to your manifest. Now, when the notification is triggered, the system will launch the full-screen intent for you.</p><ul><li><strong>Gotcha’s:</strong> System decides between when to show a notification and when to show the activity. If the user is actively using the device, then a heads up notification is displayed. If the device is idle or when the user interacts with the notification, the full-screen activity is launched. Think of receiving a phone call (heads up notification while using the phone, otherwise full-screen activity).</li></ul><p><strong>b) Hardware Identifiers<br></strong>Access to non-resettable device identifiers has been revoked in Android Q.</p><ul><li><strong>Affects: </strong>All apps running on Q (irrespective of target SDK). An exception is thrown if Target SDK is Q and a null is returned if Target SDK &lt; Q</li><li><strong>Avoid: </strong>Mac Address is now randomized, while IMEI (TelephonyManager.getDeviceId()) and serial number are no longer accessible. They are now bucketed under “privileged permissions” and are only available for carrier apps.</li><li><strong>Recommended approach: </strong>Use resettable identifiers such as Advertising ID, Instance ID or Globally-unique IDs (GUIDs). See <a href="https://developer.android.com/training/articles/user-data-ids">Best practices for unique identifiers </a>for more details on which identifier to use for which scenario.</li></ul><p><strong>c) Background Location<br></strong>Beginning with Android Q, the system will distinguish between location requests made in the foreground vs background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*7IOuJFOmHcRJfSPc" /><figcaption>The location permission request will now have 3 options: Allow all the time?. Allow only when using the app (just foreground access) and Deny (No access)</figcaption></figure><ul><li><strong>Affects</strong>: Depends. If the app targets Q then you need to request for a new background location permission. If the app doesn’t target Q, then it will automatically get this permission if it already had location access permissions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r0C-ormXfsTiqA73" /><figcaption>Image taken from Android developer docs</figcaption></figure><ul><li><strong>Recommended approach: </strong>If the app needs one-time access to the user’s location to complete some tasks, use a foreground service with the <a href="https://developer.android.com/reference/android/R.attr.html#foregroundServiceType">foregroundServiceType</a> set as location in the app’s manifest file.</li></ul><pre>&lt;service android:name=&quot;MyNavigationService&quot;</pre><pre>android:foregroundServiceType=&quot;location&quot; ... /&gt;</pre><p>If the app needs access to the device location all the time such as for geofencing, then it can set up a request for background location permission. Other aspects of the app (such as how the location is fetched and used) don’t need to change. To request access for background location, add the ACCESS_BACKGROUND_LOCATION permission to the manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5f39d1c353d82fd7f3493a4e3428257/href">https://medium.com/media/f5f39d1c353d82fd7f3493a4e3428257/href</a></iframe><ul><li><strong>Gotcha’s:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*36Cz5oh0AMROBWXF" /><figcaption>Reminder triggered by the system about app accessing location in the background</figcaption></figure><p>A couple of important things to be aware off: The user might receive a reminder after giving an app accesses device location in the background and just like any other permission, the user can revoke the background location permission that was granted to the app. This is especially critical for apps not targeting Q but running on Android Q devices since it would get the background permission by default if it had the location permission. Make sure the app gracefully handles such scenarios. For this reason, whenever the app starts a service or requests for location, check whether the user still allows the app to access location information.</p><h3>2) User Experiences</h3><h4>a) Gesture Navigation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*7jJmcpK3ZUdL5_Qr" /></figure><p>In Android Q, Google has tried to unify all the gesture navigations out there with a new gesture navigation system to replace the floating system navigation bar (back, home, and recents)</p><ul><li><strong>Affects:</strong> So if your app contains gestures, then they can possibly conflict with the system gestures. This will affect all apps that run on Android Q (irrespective of target SDK) since the system gestures will get the first dibs on handling the gesture.</li><li><strong>Recommended approach: </strong>Since the floating system navigation bar is effectively gone, it is recommended that apps now take full advantage of the new real estate available to them and provide an immersive experience to users.</li></ul><p>To build a more immersive experience, apps should draw behind the status and the navigation bar. First, request the navigation and status bar to be transparent.</p><pre>&lt;style name=&quot;AppTheme&quot;&gt;</pre><pre>......</pre><pre>&lt;item name=&quot;android:navigationBarColor&quot;&gt;@android:color/transparent&lt;/item&gt;</pre><pre>&lt;!-- Optional, but recommended for full edge-to-edge rendering --&gt;<br>&lt;item name=&quot;android:statusbarColor&quot;&gt;@android:color/transparent&lt;/item&gt;</pre><pre>&lt;/style&gt;</pre><p>Next, request your activity/view to be laid out full screen:</p><pre>view.systemUiVisibility =</pre><pre>//Layout as if the navigation bar was hidden</pre><pre>View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION</pre><pre>or</pre><pre>//Layout as if the status bar was hidden</pre><pre>View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN</pre><pre>or</pre><pre>//Layout at its most extreme</pre><pre>View.SYSTEM_UI_FLAG_LAYOUT_STABLE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*dv6HSCsZ4k6qrXAVGnR-RA.png" /><figcaption>FAB overlapping with the floating navigation bar. Floating Navigation bar enabled for ease of clarity</figcaption></figure><p>Now that the app has been laid out in full screen and behind the (transparent) system components, it could be that some clickable component of the app overlaps with the system UI. To resolve this, use Insets.</p><p>Insets are a collection of values that tell us how much to move our views by so that they don’t conflict with the system UI. This information is provided by the <a href="https://developer.android.com/reference/android/view/WindowInsets">WindowInset</a> class. Since API Level 20, Android has provided developers with System Window Insets, which tells us how much space is taken up by the system components (such as the floating navigation bar and the status bar). This information can be used to move the clickable views so that they can be clicked instead of the system UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6481e27bbce765108cc4c0faabb30b5b/href">https://medium.com/media/6481e27bbce765108cc4c0faabb30b5b/href</a></iframe><p>Similarly, beginning with Android Q, the system exposes gesture navigation insets, to move the swipeable views so that they don’t conflict with the system gestures. These are exposed through <a href="https://developer.android.com/reference/android/view/WindowInsets.html#getSystemGestureInsets()">Insets.getSystemGestureInsets()</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*Epn1TlHY19Gi7uE_81tD1Q.png" /><figcaption>System Gesture insets region highlighted in yellow.</figcaption></figure><p>But what if we don’t want to move the views and have some content in those gesture zones which might conflict with the app? In those scenarios, the app can define regions in which the app will get to consume the touch event first and not the system gestures. It can do this by passing a List&lt;Rect&gt; to the <a href="https://developer.android.com/reference/android/view/View#setSystemGestureExclusionRects(java.util.List%3Candroid.graphics.Rect%3E)">View.setSystemGestureExclusionRects()</a> API introduced in Android Q. This method is also available in <a href="https://developer.android.com/reference/androidx/core/view/ViewCompat">ViewCompat</a> as of androidx.core:core:1.1.0</p><ul><li><strong>Gotcha’s: </strong>You can only opt out of the back gesture bounds. Home gesture bounds are reserved and cannot be overridden. This is because there is only one way to exit the app. If your app conflicts with the home gesture, use WindowInsets.getMandatorySystemGestureInsets() to get the bounds of the mandatory region and shift your views out of the region accordingly.</li></ul><h4>b) Dark Theme</h4><p>Over the last year or so, we have seen a lot of apps provide support for dark theme in their apps. Android Q brings this toggle to the system setting.</p><p>There are 3 ways a user can enable dark mode:</p><ol><li>A new system setting (Settings -&gt; Display -&gt; Theme)</li><li>A new Quick Settings</li><li>Depending on the manufacturer, through Battery Saver Mode.</li></ol><p>In order to support the system-wide Dark Theme configuration, your app’s default theme should inherit from the DayNight theme. This ties the app’s main theme to the system-controlled night mode flags. This works by pulling the resources from the night qualifier folders.</p><pre>&lt;!--App Compat Style--&gt;</pre><pre>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.DayNight&quot;&gt;</pre><pre>&lt;!--Material Components--&gt;</pre><pre>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.MaterialComponents.DayNight&quot;&gt;</pre><p>If you look inside the App Compat styles, you’ll notice that DayNight theme points to AppCompat Light in the default configuration and points to AppCompat in the night configuration</p><pre>&lt;!--values/themes.xml--&gt;</pre><pre>&lt;style name=&quot;Theme.AppCompat.DayNight&quot; parent=&quot;Theme.AppCompat.Light&quot;&gt;</pre><pre>&lt;!--values-night/themes.xml--&gt;</pre><pre>&lt;style name=&quot;Theme.AppCompat.DayNight&quot; parent=&quot;Theme.AppCompat&quot;&gt;</pre><p>If you wish to provide a toggle to the users to control the theme from within the app, you can call <a href="https://developer.android.com/reference/androidx/appcompat/app/AppCompatDelegate#setdefaultnightmode">AppCompatDelegate.setDefaultNightMode()</a>, which takes in one of the four modes:</p><ol><li>MODE_NIGHT_YES — Show dark theme</li><li>MODE_NIGHT_NO — Show Light Theme</li><li>MODE_NIGHT_FOLLOW_SYSTEM — Follow System Settings</li><li>MODE_NIGHT_AUTO_BATTERY — Dark theme when the device goes into power saving mode.</li></ol><ul><li><strong>Gotcha’s:</strong></li></ul><p>a) Don’t hardcode colors. If there are hardcoded colors in layouts files, it’s a red flag. Replace them with color references. Even better: use attributes to reference colors.</p><p>b) Check drawables and provide alternate resources for them under the night qualifier</p><p>c) For vector drawables, don’t have colors hardcoded in them. Use tint to style vector resources with the correct color.</p><p>d) Make sure all color resources have corresponding alternatives inside the night folder (values-night/colors.xml)</p><p>e) If the app uses RemoteViews for notifications or Widgets, remember to test them as well. If the app uses default Notification styles, then it should be good to go since the system will handle them.</p><p>f) Configuration Change for uiMode gets invoked whenever the device switches between normal and dark mode. The user might do that manually, or it might kick in when the device battery gets low. If the app does not handle configuration changes properly, the UI will lose context when the device switches between normal and dark mode, as the visible activities and their fragments get destroyed and recreated. So, even if the UI is locked to a single orientation, please add configuration change support. Also, if the app is manually managing configuration changes via android:configChanges, there is a good chance it’ll want to manage uiMode manually as well. For example, if the app involves continuous playback (e.g., a video player), it might not want to interrupt playback just because the device switched between normal and dark mode.</p><p>A bunch of other things were also introduced in Android Q which I haven’t covered in details such as Settings Panel, a new AudioPlaybackCapture API (an API gives apps the ability to copy the audio being played by other apps. This feature is the analog of screen capture, but for audio)</p><p>Lastly, Android Q includes an updated list of restricted non-SDK interfaces whose access while eventual be shut down from the Android SDK. You can find your list of violations in the play console under the Pre Launch Report.</p><p>If you feel there is something important that I missed out, let me know in the comment below. If you found the article helpful, please applause the article and follow me on twitter at <a href="https://twitter.com/saurabh_arora90">saurabh_arora90</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199e0f8edfc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/preparing-your-app-for-android-q-199e0f8edfc6">Preparing your app for Android Q</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best practices for Video Playback in Android]]></title>
            <link>https://medium.com/viki-blog/best-practices-for-video-playback-in-android-d7482d513f3d?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7482d513f3d</guid>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Tue, 28 May 2019 14:57:39 GMT</pubDate>
            <atom:updated>2019-06-07T03:18:11.852Z</atom:updated>
            <content:encoded><![CDATA[<p>Here at Viki, we pride ourselves in offering a great video playback experience. Over the last few years, we have identified a set of experiences that every video playback app should offer to their users.</p><p><strong>Here is a summary of what we have learned (in no particular order):</strong></p><h3>(1) Keep Screen On</h3><p>This might seem obvious but we do need to tell the Android system that Video Playback is ongoing and that we want the screen to be kept on as long the user is watching the video.</p><p>When video playback begins, you can usesetKeepScreenOn(true) to let the system know. Remember to set it to false once the playback is finished or if the user leaves the playback screen.</p><h3>(2) Use System Volume</h3><p>Users are conditioned to use the volume rockers keys to control the volume of video playback. Don’t fight the system and create your own volume controls. If your design or specifications have this, try discussing if it can be avoided. It’s definitely one less thing that you need to manage.</p><h3>(3) Manage Audio Focus</h3><p>Android allows many apps to play audio simultaneously. Even though this is great, it can be very disruptive for the user, if multiple apps start to play audio at the same time. To avoid such a scenario, Android introduces a concept of Audio Focus. If your app wants to output audio, it should request for audio focus, so that the system can inform other apps to take action accordingly. From the<a href="https://developer.android.com/guide/topics/media-apps/audio-focus"> developer docs</a>,</p><blockquote>Audio focus is cooperative. Apps are encouraged to comply with the audio focus guidelines, but the system does not enforce the rules.</blockquote><p>Hence, when your app is playing audio, be a good citizen and let the system know that you are requesting audio focus. Video playback apps should ideally request <a href="https://developer.android.com/reference/android/media/AudioManager.html#AUDIOFOCUS_GAIN">AUDIOFOCUS_GAIN</a> when they are about to start playback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*OHY_hHskSMfl9cOpxP4eKA.png" /><figcaption>Be a good citizen. Prevent two audio sources from playing together</figcaption></figure><p>Also, set up an <a href="https://developer.android.com/reference/android/media/AudioManager.OnAudioFocusChangeListener.html">AudioManager.OnAudioFocusChangeListener</a> to respond to audio focus changes by pausing playback (loss of audio focus) or by reducing the playback volume (ducking). Lastly, remember to <a href="https://developer.android.com/reference/android/media/AudioManager.html#abandonAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener)">abandonAudioFocus()</a> once you are finished with the playback.</p><h3>(4) Pause/mute when headphones are removed</h3><p>Most users expect video/audio playback to mute or even pause when they unplug the headphones. If you play videos on your Mac/Windows PC, you’ll observe a similar behavior when you unplug your headphones. Be a good citizen and don’t shock the users. It’s always better to err on the side of caution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*QpmQ0EyUehLpfwpzDzaGCg.png" /><figcaption>Don’t shock the users</figcaption></figure><p>When headphones are unplugged, the Android system sends an <a href="https://developer.android.com/reference/android/media/AudioManager#ACTION_AUDIO_BECOMING_NOISY">ACTION_AUDIO_BECOMING_NOISY</a> broadcast. It is a good idea to listen for this broadcast when your video playback is ongoing and take appropriate action so as not to surprise the user with audio from the speaker.</p><h3>(5) Support headphone media playback keys</h3><p>Most headphones/earphones have media playback control keys such as play/pause, seek and next/previous videos. Users expect these keys to work seamlessly with your app. For this, Android offers <a href="https://developer.android.com/reference/android/media/session/MediaSession">MediaSession</a></p><p>MediaSession is a framework through which third-party actors can control the media session of your app. This includes not just headphones, but also other possible media controllers such as Android Wear, Google Assistant, Android Auto, etc.</p><blockquote>A MediaSession should be created when an app wants to publish media playback information or handle media keys.</blockquote><p>Through the Media Session framework, you can provide information about your current media state, such as playing, paused, buffering, etc. and also handle media keys such as play, pause, seek, etc. Third-party actors can then use this framework to create their own MediaController UI to allow the user to control the playback of your app.</p><h3>(6) Support Split Screen</h3><p>Android 7.0 added support for showing more than one window at a time. Multi-window allows the user to multitask since two apps can run side-by-side or one-above-the-other in <em>split-screen</em> mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*cbV84yKbWb6WaKGQYi4NPQ.jpeg" /><figcaption>Viki video playback in split-screen mode</figcaption></figure><p>For video playback apps, we should make sure that we do not pause the video playback when the activity lifecycle changes to onPause. Instead, we should pause video playback in onStop (in multi-window mode, the app <strong>not</strong> in focus is in pause state). Since the display window is now smaller as compared to full-screen mode, we should also take care to give maximum real estate to video playback and minimize the appearance of other controls/interactions that might appear in full-screen mode (non <em>split screen</em> mode).</p><h3>(7) Use SensorLandscape for full-screen mode</h3><p>For landscape or for portrait mode, Android offers multiple <a href="https://developer.android.com/reference/android/content/pm/ActivityInfo">orientation options</a>. If your app allows the user to switch between landscape and portrait mode, make sure you use <a href="https://developer.android.com/reference/android/content/pm/ActivityInfo.html#SCREEN_ORIENTATION_SENSOR_LANDSCAPE">sensor orientation</a> instead of <a href="https://developer.android.com/reference/android/content/pm/ActivityInfo.html#SCREEN_ORIENTATION_LANDSCAPE">regular orientation</a>.</p><p>For example, in SCREEN_ORIENTATION_SENSOR_LANDSCAPE mode, the user can hold the phone in either of the two landscape orientation and the screen will rotate to adjust accordingly. This is extremely handy for users watching videos while charging their phone, or just prefer to hold the phone in a certain manner.</p><p>That’s it! I have chosen to focus on learnings which Android developers can adopt out of the box. There are other feature sets that can be considered best practices such as PIP (picture in picture) and Mobile Data Consumption warnings but these can vary across business use cases.</p><p>If you feel there is something important that I missed out, let me know in the comment below. Or you can hit me up on twitter at <a href="https://twitter.com/saurabh_arora90">@saurabh_arora90</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7482d513f3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/viki-blog/best-practices-for-video-playback-in-android-d7482d513f3d">Best practices for Video Playback in Android</a> was originally published in <a href="https://medium.com/viki-blog">Viki Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge Android Studio’s Run Configurations]]></title>
            <link>https://medium.com/android-news/supercharge-android-studios-run-configurations-7a794d4b599d?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a794d4b599d</guid>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 14:13:09 GMT</pubDate>
            <atom:updated>2019-03-27T16:33:07.382Z</atom:updated>
            <content:encoded><![CDATA[<p>As developers we often find ourselves working on screens which aren’t the main/launcher activity. In such cases, it gets extremely frustrating and time-consuming to navigate to that activity through multiple clicks.</p><p>I always wondered if there is a quicker way to jump to the activity I was working on. Setting the activity as the launcher activity was one idea but then that required me to remember to remove it as the default once I was done with it. Upon further investigation, I learnt how custom Run Configurations can help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*hNU_yyzuX1yFm33WgPVC7A.jpeg" /><figcaption>What if I told you I could save you some time during development</figcaption></figure><h3>1) Debug Variant and Exported</h3><p>Let’s say you have two activities in your class, MainActivity and SecondaryActiity with MainActivity being the launcher activity.</p><p>If your project is using Gradle, then it most likely has debug and release build types (the defaults out of the box). Create a debug source set (generally this will go under the src folder — the same folder that has the main source set)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*hdE1-XWp-gcb2lU5pMu6qA.png" /><figcaption>`debug` source set</figcaption></figure><p>Under the debug source set, add an AndroidManifest.xml file. Include your SecondaryAcitivty in this file and set android:exported=&quot;true&quot;. This will allow Android Studio to launch this activity directly. By putting it inside the debug variant, you make sure that it isn’t exported in your release variants, so other applications cannot launch it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*S5icLr1G7fP8ncw54APtSg.png" /><figcaption>Set exported as true to allow AS to directly launch those activities.</figcaption></figure><p>When running the debug variant, the <a href="https://developer.android.com/studio/build/manifest-merge">manifest merger</a> will make sure that the values defined in debug manifest are used.</p><p>Now create a new run configuration for your app and select the SecondaryActivity as the activity to launch. In case you aren’t familiar with how to create a new configuration, here is a GIF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgCrxVD8V2L-nBC3jmz93w.gif" /><figcaption>Create a new configuration</figcaption></figure><p>Now make sure this new configuration is selected whenever you want to launch straight into the activity. This sadly doesn’t support intent parameters, so if you want to pass some information over, you are out of luck.</p><h3>2) Deeplink</h3><p>If your app supports deep links, then you can create a run configuration which takes in a URL. This will trigger the regular deep link flow, similar to a URL being clicked, and will allow you to perform your setup steps (if any).</p><p>To create a run configuration which uses deep links, select URL and then key in your deep link URL.</p><p>Hopefully, this small tweak helps remove the annoyance of having to perform multiple steps to get to the screen you are working on. If you found the tips helpful, please applause the article. For more such tips, follow me on twitter at <a href="https://twitter.com/saurabh_arora90">saurabh_arora90</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a794d4b599d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/supercharge-android-studios-run-configurations-7a794d4b599d">Supercharge Android Studio’s Run Configurations</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chrome Custom Tabs - Kotlin and Lifecycle Aware]]></title>
            <link>https://medium.com/android-news/chrome-custom-tabs-kotlin-and-lifecycle-aware-92975edaba40?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/92975edaba40</guid>
            <category><![CDATA[chrome-custom-tabs]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 19:37:51 GMT</pubDate>
            <atom:updated>2018-08-19T09:03:00.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Chrome Custom Tabs — Kotlin and Lifecycle Aware</h3><p>Recently, I needed to integrate <a href="https://developer.chrome.com/multidevice/android/customtabs">Chrome Custom Tabs</a> into our app. We wanted to <a href="https://developer.chrome.com/multidevice/android/customtabs#bestpractices">warmup</a> the browser and <a href="https://developer.chrome.com/multidevice/android/customtabs#bestpractices">pre-render</a> the content as we were in situations where we were certain that the user would go ahead and open the url. Upon going through the documentation, I came across the <a href="https://github.com/GoogleChrome/custom-tabs-client">demo app by Google</a> which shows how to integrate the library and perform the warmup and pre-render. While browsing the source code, two things stuck out:</p><ul><li>The user needs to to handle lifecycle events and manage the binding and unbinding of the Custom Tabs Service. This is a detail that can be abstracted away from the user.</li><li>The helper classes are in Java. If they were in Kotlin, we could have a shorter and cleaner API.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2702531bcb31d47cd51ed66f03df90c6/href">https://medium.com/media/2702531bcb31d47cd51ed66f03df90c6/href</a></iframe><p>To ease the integration with Chrome Custom Tabs, I quickly wrote up a version of the helpers offered by <a href="https://github.com/GoogleChrome/custom-tabs-client/tree/master/shared/src/main/java/org/chromium/customtabsclient/shared">Google</a>, in Kotlin and made it lifecycle aware.</p><p>The new <a href="https://github.com/saurabharora90/CustomTabs-Kotlin">library</a> abstracts away the service binding logic by using a LifecycleObserver.</p><p>It also adds in an extension function on the <a href="https://developer.android.com/reference/androidx/browser/customtabs/CustomTabsIntent">CustomTabsIntent</a> to launch the custom tabs with a fallback mechanism, i.e. since not all devices have the Chrome Browser, the fallback is called so that you can chose to handle the url differently, like open it in a webview.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d17f1fe5708824a7a93d498b12c3e674/href">https://medium.com/media/d17f1fe5708824a7a93d498b12c3e674/href</a></iframe><p>Designing lifecycle aware components can really help in reducing boilerplate code and make it extremely easier for users to integrate your library! So whenever you need the user to take some action in lifecycle callbacks, remember that you are asking the user to do unnecessary work and that should really be your job and not the users.</p><p>Checkout the source code <a href="https://github.com/saurabharora90/CustomTabs-Kotlin">here</a>.<br>Follow me on twitter <a href="https://twitter.com/saurabh_arora90">here</a>.</p><p>If you like the post, don’t forget to send some claps :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92975edaba40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/chrome-custom-tabs-kotlin-and-lifecycle-aware-92975edaba40">Chrome Custom Tabs - Kotlin and Lifecycle Aware</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Values.xml : Breaking down the scary creature]]></title>
            <link>https://medium.com/android-news/a-primer-on-styles-and-themes-afc801930141?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/afc801930141</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sat, 17 Feb 2018 18:10:08 GMT</pubDate>
            <atom:updated>2018-02-27T03:28:50.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*SYtk7k6NmpoRfJSvjU9oYQ.jpeg" /></figure><p>Given styles’s widespread use in Android Platform, it is surprising that there isn’t sufficient documentation from Google about how to understand and use styles on your views. I have come across multiple questions and have met various developers who have difficulties in grasping this concept. Looking at an app`s styles.xml file or even the platform/support libraries values.xml file can be daunting. Through this post, I’ll try to demystify styles and hopefully after the end of the post, you’ll be a lot more comfortable in finding you way around those scary looking files and be more confident in being able customise the look and feel of your views.</p><h3>A quick intro</h3><p>A style is just a collection of attributes that can be applied to a view. When those collection of attributes (style) is applied to a window, such as an activity, it is called a theme. Beginning with Android L, themes can also be applied to a view but we’ll get to that later.</p><p>Before we go ahead, let us also tackle attributes. An attribute is like a pointer to a value defined in your theme. By changing or customising the theme, you can change the attributes value as well. There are mostly two types/ways to use a attribute:</p><ul><li>?android:/attr : Values built in inside the Android SDK</li><li>?attr/: Values defined which we have defined or the values defined by other libraries such as the support library, design library, etc.</li></ul><p>Think of ?as de-referencing the attribute to get the value pointed by the attribute and not the actual attribute itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/786b9706e600de4ab5b7f34fc3e39c00/href">https://medium.com/media/786b9706e600de4ab5b7f34fc3e39c00/href</a></iframe><p>In the above, we have defined an AppTheme, which we have applied to the MainActivity. All the view and windows (such as an AlertDialog) inflated by the activity, will use the values referenced by those attributes.</p><pre>&lt;item name=&quot;alertDialogTheme&quot;&gt;@style/MyDialog&lt;/item&gt;</pre><p>The above implies that we are setting the the value of the attribute alertDialogTheme to a style that we have defined. Now when we create an AlertDialog with a context of the MainActivity, the alert dialog will use our MyDialog <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/app/AlertDialog.java#224">theme</a>.</p><h3>Style Inheritance</h3><p>Style inheritance is just like regular inheritance. You can share the attributes and override/add what you need. There are two ways through which you can specifiy inhertance:</p><ul><li>Explicit Inheritance: You can add a parent attribute to the style element to specify which style your current style inherits attributes from.</li></ul><pre>&lt;style name=&quot;RedBackgroundStyle&quot;&gt;<br>    &lt;item name=&quot;android:background&quot;&gt;@color/red&lt;/item&gt;<br>&lt;/style&gt;<br><br>&lt;style name=&quot;AlphaRedBackgroundStyle&quot; parent=&quot;RedBackgroundStyle&quot;&gt;<br>    &lt;item name=&quot;android:alpha&quot;&gt;0.5&lt;/item&gt;<br>&lt;/style&gt;</pre><ul><li>Implicit Inheritance: This use the . pattern to define the parent. Using the . pattern, you can easily chain styles together and keep on inheriting attributes.</li></ul><pre>&lt;style name=&quot;RedBackgroundStyle&quot;&gt;<br>    &lt;item name=&quot;android:background&quot;&gt;@color/red&lt;/item&gt;<br>&lt;/style&gt;<br><br>&lt;style name=&quot;RedBackgroundStyle.Alpha&quot;&gt;<br>    &lt;item name=&quot;android:alpha&quot;&gt;0.5&lt;/item&gt;<br>&lt;/style&gt;<br><br>&lt;style name=&quot;RedBackgroundStyle.Alpha.Lines&quot;&gt;<br>    &lt;item name=&quot;android:maxLines&quot;&gt;2&lt;/item&gt;<br>&lt;/style&gt;</pre><p>The RedBackgroundStyle.Alpha.Lines will have a red background with 0.5 alpha channel and no more than 2 lines of text.</p><p><strong>Quick Tip</strong>: The documentation mentions that you can’t inherit Android built-in styles using the dot notation, as it doesn’t reside in your namespace. This should not be confused with the support library styles since they belong to the “app” namespace and hence can be directly accessed.</p><pre>&lt;style name=&quot;TextAppearance.Demo&quot;&gt;<br>    &lt;!--This won&#39;t work as it is an Android Style--&gt;<br>&lt;/style&gt;<br><br>&lt;style name=&quot;TextAppearance.AppCompat.Demo&quot;&gt;<br>    &lt;!--This is okay as you are using a support library style--&gt;<br>&lt;/style&gt;</pre><p>Be careful to not combine the two styles together. The support library does that, but I would not recommend that for most developers. This can easily cause headaches. Consider the following example:</p><pre>&lt;style name=&quot;MyTabLayout&quot; parent=&quot;Widget.Design.TabLayout&quot;&gt;<br>    &lt;item name=&quot;tabIndicatorColor&quot;&gt;@color/red&lt;/item&gt;<br>&lt;/style&gt;<br><br>&lt;style name=&quot;MyTabLayout.Another&quot; parent=&quot;Widget.Design.TabLayout&quot;&gt;<br><br>&lt;/style&gt;</pre><p>The TabLayout to which you would apply the MyTabLayout.Another style, would not have the indicator color as red. This is because, the explicit style (which would have defined a default value of the tabIndicatorColor) attributes are always the winner unless overriden by the child style.</p><h3>Deciphering the Styles file</h3><p>Since the support library is the de-facto component in all apps, we’ll run through it’s styles file. Fire up Android Studio and search for values.xml and select the one contained inside the appcompat-support library.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2FDependableWellwornKodiakbear&amp;url=https%3A%2F%2Fgfycat.com%2FDependableWellwornKodiakbear&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FDependableWellwornKodiakbear-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="2880" height="1800" frameborder="0" scrolling="no"><a href="https://medium.com/media/66bd80294d421f75c63ab8b5b883de9c/href">https://medium.com/media/66bd80294d421f75c63ab8b5b883de9c/href</a></iframe><p>Let’s search for Theme.AppCompat.Light.DarkActionBar. As you can see, this inherits from Base.Theme.AppCompat.Light.DarkActionBar. By navigating up the parent hierarchy, you should eventually reach Base.v21.Theme.AppCompat.Light. Here you can see most of the attributes that this theme offers and what their default values are. If you go through it carefully, you should also be able to spot the alertDialogTheme attribute (it’s under Base.v7.Theme.AppCompat.Light) , which is what I used in my first example above 😉</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2FGrayReadyGermanspitz&amp;url=https%3A%2F%2Fgfycat.com%2FGrayReadyGermanspitz&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FGrayReadyGermanspitz-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="800" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f4573ece35bf2f91d023f36e0fd2fd/href">https://medium.com/media/b6f4573ece35bf2f91d023f36e0fd2fd/href</a></iframe><p>Now, if you are ever confused why your view looks a certain way or need to modify a certain attribute, you can quickly look up the theme and see what style has been applied to your view. To see what attribute a view uses to get its default style, you can look it up in the source code of the view. Here is an example for <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/SeekBar.java#79">SeekBar</a> and here is another example of a <a href="https://android.googlesource.com/platform/frameworks/support.git/+/master/design/src/android/support/design/widget/TextInputLayout.java#208">TextInputLayout</a> (The corresponding style file for this will be in the design library package). In the below GIF, you see how I quickly figure out the color of the progress track of the SeekBar</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2FLazyAgedBluebottle&amp;url=https%3A%2F%2Fgfycat.com%2FLazyAgedBluebottle&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FLazyAgedBluebottle-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="800" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ada36357d47b746f95de7dd6a5d0f714/href">https://medium.com/media/ada36357d47b746f95de7dd6a5d0f714/href</a></iframe><p>The values.xml files is huge and is just the tip of iceberg. Since android design language has changed over the years, the parent styles are distributed across API levels. Hence, I would recommend you understand how to read it and explore the values.xml file when you have some questions. It probably isn’t a good idea to try to go through it in one go, unless you are <a href="https://twitter.com/chrisbanes?lang=en">Chris Banes</a> 😉</p><h3>Android L Changes</h3><p>Beginning with Lollipop (API Level 21), a theme could also be applied to a view. This change was also added to the support library. This opens up interesting possibilities as it allows us to change attribute values at the view level, thereby not affecting the attribute values at the activity level.</p><p>As a contrived example, let’s say you have a scenario in which you have a CheckBox and a SeekBar in the same activity and you want them to have different colors. As we saw above, the SeekBar’s track drawable uses the colorControlActivated attribute as its track color. Checkbox also uses the same attribute for it’s checked state color. Now if you dig through the values.xml file of the appcompat-support library, you’ll notice that the colorControlActivated attribute refers to the value of the colorAccent attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61AjWHUDAVnFQsyYDLnmFA.png" /><figcaption>`colorControlActivated` same as `colorAccent` attribute</figcaption></figure><p>Now if we want to change the track color of the SeekBar, we can just create a new theme which changes the value of the colorControlActivated or the colorAccent attribute to our chosen color and apply that theme to our SeekBar. You cannot do this via a style, since colorControlActivated is an attribute and you can only change the value of an attribute through a theme and not through a style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ed7cc0e8190ac54680c59278f83373b/href">https://medium.com/media/4ed7cc0e8190ac54680c59278f83373b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qctVqgOoJJAwQ4icGjzbg.png" /><figcaption>SeekBar color changed while Checkbox still uses the activity theme</figcaption></figure><p>This is much easier and future proof than copying over the SeekBar track drawable into your app’s resources directory and then making changes in it. The ability to use a theme on the view is what makes this all possible.</p><p>I have tired to touch all the pain points to demystify styles and I hope this will make you much more confident when you have to deal with them again. In a follow up post, I’ll try to combine all three (styles, themes and attributes), to build an action view for a menu item, in a manner that it looks just like the native menu item and automatically adapts across all OS versions and screen sizes. The post will be linked here when it is ready.</p><p>If you feel that I missed out on something or made some mistake or have suggestion on how I could improve, feel free to reach out to me on <a href="https://twitter.com/saurabh_arora90">twitter</a>. If you liked this post or learned something, please remember to<strong> applaud it by pressing the 👏 button and do share it </strong>😃</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afc801930141" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/a-primer-on-styles-and-themes-afc801930141">Values.xml : Breaking down the scary creature</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android app optimization techniques]]></title>
            <link>https://medium.com/viki-blog/optimise-because-performance-matters-2ae3ba78fb1a?source=rss-cf7384765f9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ae3ba78fb1a</guid>
            <category><![CDATA[android-performance]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Saurabh Arora]]></dc:creator>
            <pubDate>Sat, 13 Jan 2018 05:33:22 GMT</pubDate>
            <atom:updated>2018-01-15T02:45:27.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*YT6MKAEWxq-ikXoMBcVX9g.jpeg" /></figure><p>At <a href="https://www.viki.com/">Viki</a>, we have spent the last couple of months focussing on improving our app performance and data consumption. With the <a href="https://design.google/library/ux-next-billion-users/">Next Billion Users</a> (NBU’s) expected to come on board within the next few years, new markets will open up for the app developers. With the launch of Android Go, even Google has doubled down on its efforts to bring a great Android experience to first time internet users.</p><p>Through this post, we will focus on three aspects: Memory Consumption, Data Usage and APK size.</p><h3>Reducing Memory Footprint</h3><p>In order to benchmark memory footprint, it is important that we use the same device for all the tests as the memory consumption will tend to differ across device classes. In our Android app, we use heuristics to decide if the app should use Exoplayer or the native MediaPlayer; which makes it even more important that we maintain the same test environment.</p><p>The new profilers with Android Studio 3.0 has made it really easy to take heap dumps and identify high memory consuming objects. From the first heap dump we saw something that we expected, bitmaps are the top of the chart. Like other apps, we have images bundled inside the app and some served over the web. Before we look into how we addressed them, I would like to highlight how we identified the specific images. With the new Memory Profile, when you take a heap dump, it will list down the objects currently consuming memory. Upon selecting the bitmap objects, it offers a preview of the bitmap as well. One thing I noticed is that this bitmap preview is only available when I profile devices running Android N and below. On Android O devices, the heap dump does not show a preview of the bitmap making it extremely hard to profile. Hopefully Google addresses this soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTEhYfbDp7CeaGpe2JIIEw.png" /><figcaption>Heap Dump on an Android N Device. On an Android O device, the Bitmap Preview isn’t visible</figcaption></figure><ul><li>For <strong>images downloaded from the Web</strong>, we used a server configured image resizing service so that we could request images of certain dimensions and hence download smaller images. To make sure that we maintained a high cache hit ratio on our CDN, we split the dimensions into density buckets</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*UaSiWxvAlm4N_oQDP-BZdQ.png" /><figcaption>Resolution requested depends on screen density</figcaption></figure><ul><li>For <strong>bundled images,</strong> we noticed that our placeholder images were taking a lot of memory. These are used when images are being downloaded from the web. Even though we were using one placeholder, there are multiple views rendered on the home page (20+ views depending on the logged in user) and since each view needs a placeholder, the memory consumption quickly adds up. For these, we worked with our design team to use a single color image as a placeholder for low memory devices. Android provides a <a href="https://developer.android.com/reference/android/app/ActivityManager.html#isLowRamDevice()">isLowRamDevice</a>()to identify if a device is a low memory device.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dba35214684b9312a6e2532ed0b38b8/href">https://medium.com/media/5dba35214684b9312a6e2532ed0b38b8/href</a></iframe><p>On a low memory device, this reduced our footprint by 14%.</p><p>The next candidate on our heap dump was a surprising one; Descriptions and Titles of shows. At Viki, we pride ourselves in supporting many languages (20+ for some of the popular shows), and hence we have translations of metadata in all those languages and these are sent down to the client. Since descriptions of shows/celebrities could be very long, these strings were consuming a lot of memory. Also users rarely change their phone language, so we decided to only store the translations of the user’s current language and use English as a fallback. The fallback mechanism allowed us to cover for the scenario where a user might change their language during the usage of the app. This way, they would see descriptions in English until they restarted their app, where then we might be able to fallback to their native language, if supported.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cabdd15828a3f931d66e139d53172aa/href">https://medium.com/media/4cabdd15828a3f931d66e139d53172aa/href</a></iframe><p>The last candidate that we attacked were the view objects. Various Android talks throughout the years have tired to highlight the benefits of a flat hierarchy for performance reasons. In our scenario, we started seeing improvements on memory consumptions as well (recycler view item layouts quickly add up), since less objects were now being stored in memory. We used ConstraintLayout to flatten the view hierarchy and only modified the offending ones. It does not make sense to go on a clean driving throughout the app and might be premature.</p><p>All of these changes helped bring down our memory footprint by about 27% on low memory devices (with the extra placeholder optimisations) and by about 18% on other devices.</p><h3>Reducing Data Consumption</h3><p>For our data consumption, we decided to attack the low hanging fruits such as enabling WebP support (and maintaining backwards compatibility on devices that don’t support WebP). The image resizing service also allowed us to reduce the size of images that were being downloaded as we were no longer downloading the full sized image.</p><p>Furthermore, we decided to half the items per-page count for specific devices and regions (payloads add up when you have multiple language translations in them ;) ). We are also looking forward to removing those un-needed translations from payload to further reduce the data transfer.</p><h3>Reducing APK Size</h3><p>Proguard is one sure way to remove dead and unwanted code from your APK. Once enabled, you should instantly see its benefits reflected in your APK size. At Viki, we already had this enabled, so we decided to explore more options. We ran most of our images through <a href="https://tinypng.com/">TinyPNG</a> and save big reductions in their sizes. Tiny PNG dramatically reduces each image by up to 75% (your mileage may vary). This in itself reduced our APK size by 15% without any visual difference in the graphics.</p><p>Another quick tip that I would like to highlight is the use of resConfig inside your build.gradle file. Since most libraries (especially Support library and Play Service library) include translations for many many languages, you should strip them out if you don’t support them. Resources are know to take up a lot of space and this quick tip should get that down ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*3EPxSawq5yatsrom_WfoIQ.png" /><figcaption>How resConfig shaved off nearly 1Mb for us</figcaption></figure><p>These efforts helped us reduce our APK size by about 25%</p><p>Overall, this effort put in over the last few months has been very rewarding. The icing on the cake was Viki being announced as one of the launch partners for Android GO.</p><p>Remember #perfMatters</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ae3ba78fb1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/viki-blog/optimise-because-performance-matters-2ae3ba78fb1a">Android app optimization techniques</a> was originally published in <a href="https://medium.com/viki-blog">Viki Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>