<?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[freenet Engineering - Medium]]></title>
        <description><![CDATA[Software Engineers at freenet build a variety of web, mobile, desktop and backend applications. This is our engineering blog. - Medium]]></description>
        <link>https://medium.com/freenet-engineering?source=rss----3a7d5106526c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>freenet Engineering - Medium</title>
            <link>https://medium.com/freenet-engineering?source=rss----3a7d5106526c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:41:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/freenet-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Running Android Espresso Tests with Data Binding (and koin)]]></title>
            <link>https://medium.com/freenet-engineering/running-android-espresso-tests-with-data-binding-and-koin-a57a8d38daa5?source=rss----3a7d5106526c---4</link>
            <guid isPermaLink="false">https://medium.com/p/a57a8d38daa5</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Daniel Hartwich]]></dc:creator>
            <pubDate>Mon, 29 Apr 2019 08:52:22 GMT</pubDate>
            <atom:updated>2019-04-29T08:56:02.953Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, we at <a href="https://www.freenet.de/">freenet.de</a> started working on an application that uses the <a href="https://developer.android.com/topic/libraries/data-binding/">data binding library</a>.</p><p>Data binding was presented by <a href="https://www.youtube.com/watch?v=5sCQjeGoE7M">Google already in September 2015</a> but has evolved and improved quite a bit. It’s now officially part of <a href="https://developer.android.com/jetpack/">Android Jetpack</a> that we developers love to use in our projects in order to <em>reduce boilerplate, accelerate development </em>and <em>build high quality, robust apps.</em></p><p>For this application we had to build a feature that simply displays a list of items and of course we were using data binding for it.</p><p>Building the screen was fast and simple and with the help of data binding, we could just pass my items to the adapter and let the binding handle all the rendering and assigning of values to their respective views. So in no time we had the screen up and running and we were ready to submit a pull request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1WW2L2V5I8hWyFlaCHb0yg.jpeg" /><figcaption>There’s always more to do!</figcaption></figure><h4>We hadn’t thought about tests yet (well, we kind of had already 😉)</h4><p>Of course, we wanted to have tests to ensure that everything <em>looks</em> as expected (UI tests) and that everything <em>works</em> as expected (Unit tests). While Unit tests were easy to write and through <a href="https://site.mockito.org/">mockito</a> we can mock the dependencies to other components, it was not straightforward when we wanted to write UI tests.</p><p><strong>Things got interesting when we tried to write espresso tests…</strong></p><p>Well, in theory it should be easy, because all we need to do is mock the ViewModel, that is emitting view states, which will be rendered by the activity (or fragment) and afterwards make sure that the expected data is visible.</p><p>Turns out this is easier said than done:</p><p><strong>How to make sure that the activity you are starting uses your ViewModel instance?</strong></p><p>In the application we are working on we are using <a href="https://github.com/InsertKoinIO/koin">koin</a> to inject our dependencies. Through this, we are also injecting our view models into our fragments and activities, and this is where we need to hook in. In the setup block of our espresso test we can add our view model to the dependency tree by calling loadKoinModule().</p><p>It’s also important to say that in order to override koin modules that are implemented in the Main App, you should have a custom TestApplication and a custom JUnitRunner (check out the example that is linked below to see how to do it).</p><p>So now, we just need to observe changes of our LiveData&lt;ViewState&gt; and check that the changes get rendered as expected. This worked fine in the beginning, but after adding a few more tests, we ran into issues, that the tests became flaky, because the data binding had not finished yet and we worked around this by putting Thread.sleep(400) in our tests as a quick fix. But this is not the solution we want. We want something more optimal, so we began researching… After a short amount of time we found <a href="https://stackoverflow.com/a/52390905">this</a> Stack Overflow answer, that gave us the much needed hint:</p><blockquote>Espresso does waitForIdle before executing view checks. waitForIdle goes thought IdlingRegistry and waits until every IdlingResource is idle.</blockquote><blockquote>LoopingIdlingResource is used in Espresso by default. It waits until looper doesn&#39;t have messages in queue, which means that it is idle.</blockquote><blockquote>However DataBinding uses different approach to schedule an update, it uses Choreographer.postFrameCallback. So updates are not posted into looper queue and Espresso will not wait for them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*UV40YyFJkUlAnROtJ8iOVg.png" /></figure><p>This means, we need our own IdlingResource that looks at our data bindings and allows the test to proceed when all the data binding is finished. Luckily in the same answer, there were also two links to a google-samples repository that already had a partial a solution for our problem:</p><p>A <a href="https://github.com/googlesamples/android-architecture-components/blob/7f861fd45d158e6277a3c35163c7f663e135b2cf/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/util/DataBindingIdlingResource.kt">DatabindingIdlingResource</a> that works for Fragments and a <a href="https://github.com/googlesamples/android-architecture-components/blob/7f861fd45d158e6277a3c35163c7f663e135b2cf/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/util/DataBindingIdlingResourceRule.kt">DatabindingIdlingResourceRule</a> that needs to be applied in our test in order to wait for the DatabindingIdlingResource to idle.</p><p>The only remaining problem is, that we need the DatabindingIdlingResource to also wait for Activities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628c61ccb2f4b1457536dbfeb5a923a5/href">https://medium.com/media/628c61ccb2f4b1457536dbfeb5a923a5/href</a></iframe><p>Now it works with activities and fragments…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*qD4s47WEYb-31O3g_rdZnA.jpeg" /><figcaption>One more… oh yea 🎉</figcaption></figure><p>After applying the new IdlingResource in our test we were happy and we thought the tests would finally all be green, but just shortly after running them 2 or 3 times we figured out, that they are still broken / flaky. What were we missing?</p><p>And then it struck us… The adapter is also using data binding so we have something like a data bindingception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FCaMKDO45sdo1v2bDKzEIg.jpeg" /></figure><p>So one last step to get our tests to run is to wait for all the children of theRecyclerView to finish their binding before we run our test assertions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7acd91d4d17303013068848c247ab7fa/href">https://medium.com/media/7acd91d4d17303013068848c247ab7fa/href</a></iframe><p>And that’s it… now Espresso waits until all data bindings have been finished before it starts executing.</p><p>We thought this is a nice and small piece of information to share that can be really helpful when you want to write Espresso tests (kudos to you already) and you are using data binding + koin.</p><p>Feel free to check out the small <a href="https://github.com/dhartwich1991/databinding-espresso">example project on GitHub</a> we created and if this article helped you to solve a problem or you just enjoyed reading it, feel free to smash the clap button below to give me feedback. 👏</p><p>We are also more than happy to receive any kind of comments!</p><p><a href="https://github.com/dhartwich1991/databinding-espresso">dhartwich1991/databinding-espresso</a></p><p><em>Interested in how we develop software? </em><a href="https://stellenangebote.freenet-group.de/stellenangebote.html?sid=06aa4ffaee857ab350a7a7fcbb1061da"><em>Join our team in Hamburg, Germany!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57a8d38daa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/freenet-engineering/running-android-espresso-tests-with-data-binding-and-koin-a57a8d38daa5">Running Android Espresso Tests with Data Binding (and koin)</a> was originally published in <a href="https://medium.com/freenet-engineering">freenet Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful tips to inspect your Android app — Part 2]]></title>
            <link>https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-2-ced14ec6740f?source=rss----3a7d5106526c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ced14ec6740f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Georg Modzelewski]]></dc:creator>
            <pubDate>Fri, 27 Jan 2017 07:17:38 GMT</pubDate>
            <atom:updated>2017-01-27T07:17:38.354Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-1-34415239e91a#.4kkscur2q">In the first part of this article</a> we introduced ways to improve your Android app, your workflow and how to detect memory leaks. This article provides further information concerning all kind of measurement tools, technical debt identification and APK analysis.</p><h3>Measurements (Request times, memory consumption, fps)</h3><p>Your Android device runs at approximately <em>60</em> <em>frames per second (fps)</em>. The main reason for <em>60fps</em> is due to the inner workings of the human eye. A camera only takes one shot and that’s it. The human eye constantly communicates with the brain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*IDJIEGSIIy5Gh_Os48W15Q.png" /><figcaption>A picture is only recorded once, the human eye records constantly instead</figcaption></figure><p>The reason why we see motion in the visual information is the flip-book effect, by displaying images fast enough we can trick the human brain into perceiving motion when there actually isn’t any. The caveat here is that how fast we display those images has a large effect on how fluent the motion will actually look to us.</p><p>The human eye starts to perceive motion at around 10–12fps, although it does not appear really smooth. <em>24fps</em> allows the human eye to see fluent motion, but that’s only thanks to visual effects like motion blurring. <em>30fps</em> is enough for movies, but you still need cinematic effects to be really convincing.</p><p>While <em>60fps</em> is actually the so called <em>sweet spot</em>. Great, smooth motion without all the hacks, and most humans can’t perceive the benefits of going higher than this number. It is worth noting that the human eye is very discerning when it comes to inconsistencies in these frame rates. E.g. if you are moving along at <em>60fps</em> and you suddenly drop to <em>50fps</em> your user will see the difference as a lack of smoothness.</p><p>As your app developer your goal is to keep your app at <em>60fps</em> and keep it there throughout all kind of tasks which involve your app.</p><blockquote>1000 ms / 60 fps = 16.667 ms / frame</blockquote><p>So, if your want your app framerate to not drop below <em>60fps</em>, you as an app developer can’t block the UI thread for more than <em>16.667 ms</em>.</p><p>The simplest tool to display the current framerate is the <em>Android GPU rendering view</em>. I created a small video to see how to activate the GPU profiling view in the developer options, created on my Xiaomi Mi5:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcncxZyywcO4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcncxZyywcO4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcncxZyywcO4%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a22b06ef873a3e8cc7bb88be7b980a8/href">https://medium.com/media/3a22b06ef873a3e8cc7bb88be7b980a8/href</a></iframe><p>In the video you can see the colored sections of the graph, and what phase of the rendering pipeline each color represents.</p><p>The green line represents the <em>16.667 ms</em> threshold. To achieve <em>60fps</em>, the vertical bar for each frame needs to stay below this mark. Any time a bar pushes above this line, Android may be forced to drop frames.</p><p>Each bar has a blue, purple, red, and orange component. The blue section of the bar represents the time used to create and update the View’s display lists. If this part of the bar is tall, there may be a lot of custom view drawing, or a lot of work in onDraw methods.</p><p>The purple section of the bar represents the time spent transferring resources to the render thread. The red section of the bar represents the time spent by Android’s 2D renderer issuing commands to OpenGL to draw and redraw display lists. The height of this bar is directly proportional to the sum of the time it takes each display list to execute.</p><p>The orange section of the bar represents the time the CPU is waiting for the GPU to finish its work. If this bar gets tall, it means the app is doing too much work on the GPU.</p><p>For gamers and PC tuning enthusiasts exists a small library, to view the fps in the app. The <a href="https://github.com/wasabeef/Takt"><em>Takt</em></a> library shows a small view in the right bottom of the screen with the current framerate. To get started you add the dependency into your <em>build.gradle</em> file and call the <em>Takt</em> install factory method with your application context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*u_CeH2HzSWeobj9zHeDvMw.png" /><figcaption>The Takt library view in the debug build of the <a href="https://play.google.com/store/apps/details?id=de.freenet.pocketliga&amp;hl=de">PocketLiga app</a></figcaption></figure><p>In order to stay at the sweet spot <em>60 fps</em> you should identify and fix performance issues. One way to achieve that is to measure the execution time of a method. You could write your own timers which computes this execution time or even better, use the <a href="https://github.com/JakeWharton/hugo"><em>Hugo</em></a> library. It reduces the timer code to a simple annotation (@DebugLog). It also works nicely with the <em>PID Cat</em> logger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*BjoVp403SZ-PSV1fwymnuw.png" /><figcaption><a href="https://github.com/JakeWharton/hugo">Hugo</a> annotation-triggered method call logging</figcaption></figure><p>Another way to identify performance issues is to measure object creation time. A simple tool here is <a href="https://github.com/frogermcs/AndroidDevMetrics"><em>AndroidDevMetrics</em></a>. It starts via notification at app start, clicking the notification you are presented a view listing the creation time of all objects in your app.</p><p>To get started you add the dependency into your <em>build.gradle</em> file and call the <em>AndroidDevMetrics</em> init factory method with your application context. When installed, you will get a notification at app start.</p><p>Below a custom example with a modified TakesTooLongAnalyticsTracker object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*Nnl-LaIdIrh48lvV." /><figcaption><a href="https://github.com/frogermcs/AndroidDevMetrics">AndroidDevMetrics</a>: Object creation time measurements of dagger objects</figcaption></figure><p>One of the most versatile Android analysis tools is Facebook’s <a href="http://facebook.github.io/stetho/"><em>Stetho</em></a>. You register your application context at app start with <em>Stetho</em> and you’re good to go. To start <em>Stetho</em> you need an Google Chrome browser, just call <em>chrome://inspect</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0GL27RlgvKyQuH4M." /><figcaption>Chrome inspect view to start <a href="http://facebook.github.io/stetho/">Stetho</a> app</figcaption></figure><p>The plugin establishes a connection to the Google Chrome Developer Tools, which shows informations regarding view hierarchies, network request times and the current database status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnuQtrUE-Dh2dL9MGmc5ww.png" /><figcaption><a href="http://facebook.github.io/stetho/">Stetho</a> database inspection</figcaption></figure><p>You can even inspect the database objects that are shown at the time the app is used, which previously was only possible on rooted devices. For network request support you will need to inject an observer into you network stack. If your are using OkHttp you need to add <em>Stetho’s</em> network interceptor into your <a href="https://github.com/square/okhttp"><em>OkHttp</em></a> client. For those using a <em>HttpUrlConnection</em>, <em>Stetho</em> provides its own <em>StethoUrlConnectionManager</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*9ZnehvoAsxuPz8n-A_NVXw.png" /><figcaption><a href="http://facebook.github.io/stetho/">Stetho</a> network inspection</figcaption></figure><p>Another very useful feature of the <em>Stetho </em>library is <em>Stetho Dumpapp</em>, which allows creation of custom command line interfaces to your application components. Afterwards those interfaces can be used to manipulate the object states from your command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*j7Lo9Obq0QNqRM-dmFMeiQ.png" /><figcaption>Stetho Dumpapp</figcaption></figure><p><a href="https://www.charlesproxy.com/"><em>Charles</em></a> is a network monitor that allows inspection of SSL/HTTP(S) traffic between his machine and the Internet. This includes both complete requests and responses and the HTTP headers (which contain the cookies and caching information). To use that tool you don’t need to make changes in your app at all, which makes it favorable in quality assurance testing. You just need to connect your phone via an Ad-Hoc WLAN network from your computer to the internet and configure your device to use the Charles proxy. For further information, including a SSL proxying tutorial, please visit the <a href="https://www.charlesproxy.com/documentation/"><em>Charles documentation</em></a>.</p><p><a href="http://www.sonarqube.org/"><em>SonarQube</em></a> is a continuous quality analysis platform to inspect your code, which also make suggestions to increase the overall code quality and reduce the technical debt. It can be extended through plugins, and usually embeds tools and checks. The Android support comes out-of-the-box and should be used as a gradle task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6g1WTZL1uWcXBtkti230w.png" /><figcaption><em>SonarQube </em><a href="http://docs.sonarqube.org/display/PLUG/GitHub+Plugin"><em>Github reporting</em></a></figcaption></figure><p>A quite valuable feature is the <a href="http://docs.sonarqube.org/display/PLUG/GitHub+Plugin"><em>Github reporting support</em></a> which allows <em>SonarQube</em> to commit reports into your <em>Github</em> pull request as a comment. It even makes suggestions to code located around your modifications.</p><p>Thanks to <a href="https://www.docker.com/"><em>docker</em></a>, installing <em>SonarQube</em> is a breeze and that setup should be sufficient for most applications. Here a small step-by-step tutorial to get <em>SonarQube</em> up and running:</p><ol><li>Install <a href="https://www.docker.com/"><em>docker</em></a></li><li>Run: docker pull sonarqube</li><li>Run: docker start sonarqube</li><li>Navigate to localhost:9000</li><li>Log in with default credentials (username: <em>admin</em>, password: <em>admin</em>)</li></ol><p>Change to the Administration tab and click on the <em>System → Update Center</em> button. Here you can install Plugins, like the <em>Github</em> Plugin for reporting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YVDvN3vvFa6heK_B." /><figcaption>SonarQube Plugin Update Center with the Github Plugin</figcaption></figure><p>Your <em>Github</em> reporting is now up and running. Now you need to get <em>access tokens</em> for <em>Github</em> and <em>SonarQube</em>.</p><p>You can create a <em>Github access token</em> on the <em>Github</em> settings page. Make sure the access token has at least the public_repo scope (repo for private repositories).</p><p>To get a <em>SonarQube access token</em>, create a user in <em>SonarQube</em> (<em>Administration → Security → Users → Create User</em>) and generate a token.</p><p>After you installed the <a href="https://plugins.gradle.org/plugin/org.sonarqube"><em>SonarQube Gradle</em></a><em> </em>plugin in your project’s build.gradle files, add the following lines of code into your app’s build.gradle (recommended above the dependencies block):</p><pre>sonarqube {<br>    properties {<br>  property ‘sonar.projectName’, getProject().name<br>  property ‘sonar.projectKey’, android.defaultConfig.applicationId<br>  property ‘sonar.projectVersion’, android.defaultConfig.versionName<br>  property “sonar.tests”, “src/test/java”</pre><pre>// first defines where the java files are, the second where the xml files are<br>  property “sonar.sources”, “src/main/java,src/main/res”<br>  property ‘sonar.sourceEncoding’, ‘UTF-8’<br>  property ‘sonar.login’, &lt;YOUR SONARQUBE ACCESS TOKEN&gt;<br>  property ‘sonar.host.url’, ‘localhost:9000’<br>  property ‘sonar.analysis.mode’, ‘preview’<br>  property ‘sonar.github.oauth’, &lt;YOUR GITHUB ACCESS TOKEN&gt;<br>  property ‘sonar.github.repository’, &lt;THE NAME OF YOUR REPO, SONARQUBE HAS &#39;SonarSource/sonarqube&#39;&gt;<br>  property ‘sonar.github.pullRequest’, &lt;THE ID NUMBER OF YOUR PULL REQUEST&gt;<br> }<br>}</pre><p>Now add the <em>Github</em> and <em>SonarQube</em> auth tokens into the equivalent fields. You can start the build process via the <em>SonarQube Gradle</em> task.</p><p>The caveat of the local deployment is you have to add your repository name and pull request number manually. For testing reasons it should be sufficient, but as a professional developer you should consider installing <em>SonarQube</em> on a deployment machine and let your continuous integration tool fill these fields for you.</p><p>The <em>Github</em> plugin uses the <em>SonarQube</em> server to inspect your commit and post issues into your pull request. It is not intended (and since the newest version prohibited) to upload anything to your <em>SonarQube</em> server.</p><p>The intended workflow to develop with <em>SonarQube</em> is <em>Github</em> plugin inspection at committing to a pull request and <em>SonarQube</em> analysis at merge into the master branch. If you want to run a <em>SonarQube</em> analysis <em>Gradle</em> task, just remove the sonar.github.* properties and change the sonar.analysis.mode property to &#39;publish&#39;.</p><p>We have seen many ways to measure your app, from request times to memory consumption, from framerate up to object creation times and even a way to measure your overall code status. These involve operations from the inside of your running app, but what about the analysis from the outside of your app? That’s the purpose of the next section.</p><h3>Apk Analyze</h3><p>The final build process will result in an <em>APK</em> (Android package) file. A good start to analyse its content is offered by Android Studio. The <em>APK Analyzer</em> window provides immediate insight into the composition of the APK. You can inspect the absolute and relative size of files in the <em>APK</em> (such as <em>DEX</em> and Android resource files), open final versions of files in the <em>APK</em> (such as the AndroidManifest.xml) and perform a side-by-side comparison of two APKs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fo8Z5JVeduHe89eT." /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_00jd8-vrewCiTug." /><figcaption>Android Studio APK Analyzer</figcaption></figure><p><a href="https://github.com/google/battery-historian"><em>Battery Historian</em></a> is a tool to inspect battery related information and events on an Android device running Android 5.0 Lollipop (API level 21) and later. It allows application developers to visualize system and application level events on a timeline with panning and zooming functionality to inspect the metrics that impact battery, specific to the chosen application. It is a web application written in <a href="https://golang.org/"><em>Go</em></a>. Please check the <a href="https://github.com/google/battery-historian">homepage</a> for further information how to get started.</p><p>If the webpage is up and running, you load a bug report from your app (which you get via terminal command: adb bugreport &gt; bugreport.txt and start your analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpswC1IEa98rJirh." /><figcaption><a href="https://github.com/google/battery-historian">Battery Historian</a> energy consumption inspection tool</figcaption></figure><p>Another quite popular tool is <a href="https://github.com/google/android-classyshark"><em>Classyshark</em></a>. <em>Classyshark</em> is a Java application for method counting that is executed via the following console command (java -jar Classyshark.jar).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2ZW_ipPVjMxHIS_e." /><figcaption><a href="https://github.com/google/android-classyshark">Classyshark</a> method count tool</figcaption></figure><p><a href="https://github.com/google/android-classyshark"><em>ClassyShark</em></a> is a standalone binary inspection tool for Android developers. It is used for method counting which supports you in order to make sure that your app stays below the <a href="https://developer.android.com/studio/build/multidex.html">notorious <em>64k reference limit</em></a>.</p><p>To solve this problem you can use the <em>Multidex</em>-workaround which is a performance drawback for your app due to higher allocation times or set your <em>minSdk</em> to Android 5.0 or higher. Android 5.0 introduces a runtime called <em>ART</em> which natively supports loading multiple <em>DEX</em> files from <em>APK</em> files. <em>ART</em> performs pre-compilation at app install time which scans for <em>DEX</em> files and compiles them into a single <em>.oat</em> file for execution by the Android device.</p><p>At the time this article was written, by setting your minSdk to Android 5.0 you would exclude 39,3 % of potential Android users the access to your app (S<em>ource: </em><a href="https://developer.android.com/about/dashboards/index.html%29."><em>https://developer.android.com/about/dashboards/index.html</em>).</a> The favorable alternative is, you could check, if you can remove one of the bigger libraries in your project which are only rarely used. A good starting point is the popular <a href="https://github.com/google/guava"><em>Guava</em></a> library, which counts 14824 methods.</p><p>This article provides some tips and tool suggestions to measure your app. This is not a complete list and you should have a look which tools give the most benefit for your scenario.</p><h3>BONUS ProTip:</h3><p>We have seen that many of the libraries use the context of your app. To implement them it is important not to intervene with the rest of your app. A protip here is, make extended use of the Android implicit build types. The <em>debug</em> build type is the favorable way to implement this tools. At first you should make the build.gradle dependency only available in the debug build. You can put the build type as a prefix before the <em>compile </em>command<em>.</em></p><pre>debugCompile &#39;com.facebook.stetho:stetho:1.4.1&#39;</pre><p>Create a <em>DebugTools</em> interface in your main project and write a factory method to initialize:</p><pre>public interface DebugTools {<br>    /**<br>     * Initialize debug tools. Should be called in the application.<br>     *<br>     * @param context The application context.<br>     */<br>    void initialize(@NonNull Context context);<br>}</pre><p>Create a <em>DebugToolsImpl.java</em> class in your main build type which implements the DebugTools interface, but does nothing at initialize. Create a <em>DebugToolsImpl</em> class in your debug build type, which initializes all the fancy tools you like.</p><pre>public class DebugToolsImpl implements DebugTools {<br>    @Override<br>    public void initialize(@NonNull Context context) {<br>        Stetho.initializeWithDefaults(context);<br>    }<br>}</pre><p>If you use dagger, provide a DebugTools object in your Module, inject it in your Application class and call the initialize method with your context.</p><p>Your main app should now be nice and clean.</p><p>And that’s it. I hope you learned something and next time you think you have problems in your app, you start scratching precisely where it itches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*nvEM--365U4Ekf6j." /></figure><p><em>Interested in how we develop software? </em><a href="https://stellenangebote.freenet-group.de/stellenangebote.html?order[dir]=asc&amp;order[field]=stellenbezeichnung&amp;filter[countr][]=474&amp;filter[radius_search_location]=&amp;filter[radius_search_range]=25&amp;filter[aufgabengebiet_id][]=21&amp;filter[volltext]="><em>Join our team in Hamburg, Germany!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced14ec6740f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-2-ced14ec6740f">Useful tips to inspect your Android app — Part 2</a> was originally published in <a href="https://medium.com/freenet-engineering">freenet Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful tips to inspect your Android app — Part 1]]></title>
            <link>https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-1-34415239e91a?source=rss----3a7d5106526c---4</link>
            <guid isPermaLink="false">https://medium.com/p/34415239e91a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Georg Modzelewski]]></dc:creator>
            <pubDate>Thu, 19 Jan 2017 14:31:34 GMT</pubDate>
            <atom:updated>2017-01-27T07:18:46.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*K4ktR0XDllVJ49RG." /></figure><p>There are many reasons why the analysis of your Android project is quite a good idea. Besides finding and extinguishing bugs successfully and quickly improving user experience you may also want to speed up your processes to avoid senseless waiting, or become familiar with a new project while doing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/0*bqoDergxGoLSIIul." /></figure><p>There are lots of tools to track down memory leaks, one of the most common bugs in Android apps. Other tools help you find code smells. In addition, all kinds of tools exist to analyze the finished Android package files (apks), to collect data concerning the famous 64k method limit or to reduce the general app size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*yaI9OQYACuSIvQjb." /></figure><p>The intention of this article is to get a feeling for when to use which tool for what kind of job. The two principles here are:</p><blockquote>Know your tools</blockquote><p>and</p><blockquote>Use the right tools for the right job</blockquote><h3>General</h3><p>At first some general recommendations to speed up your development processes. If you have recently used a virtual machine and you work on an Intel processor, you should consider activating <a href="https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager"><em>Hardware Accelerated Execution Manager (HAXM)</em></a> support, which allows you to run code directly on your host hardware without emulating it. The only drawback here is that your Android VM must be an Intel Atom image which excludes native ARM code.</p><p>Download the tool via your Android SDK Manager which will install the package to android-sdk/extras/intel/Hardware_Accelerated_Execution_Manager. Make sure the virtualization support is activated in your BIOS settings before installing HAXM. If your VM starts with <em>HAXM</em> your console output should show some output which mentions HAX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*eAa3jVPLFIMSQLNW." /><figcaption>HAXM enabled VM starting console output text</figcaption></figure><p>The performance improvement between ARM and Intel Atom Builds is about 90 %, activating HAXM will get you another 30%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*xX_GTloLsvWl0zRPgFyt0A.png" /><figcaption>First boot time (tested on a MacBook Pro i5, late 2013)</figcaption></figure><p>If you want to work on your desktop but use your physical device instead of a VM, it is annoying to constantly change input devices and it slows down your development process significantly. Instead, a convenient solution would be to simply mirror the screen of your physical device to your desktop.</p><p>Prior to Android 5.0 the only way to receive at least screenshots was to use the command line command adb screencap -p, which is very slow. Since Android 5.0 it has been possible to get direct access to the graphic buffer, at least if you have root permissions. However, this feature was blocked in Android 7.</p><p>Plenty of tools will help you with presenting apps from your physical device by mirroring your device screen into a window on your desktop. One of them is <a href="https://www.vysor.io/"><em>Vysor</em></a>. It’s free, but ads are shown every now and then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/0*EtC-uRCj5hvfpM03." /><figcaption>Vysor showing the <a href="https://www.youtube.com/watch?v=F-fluUQApO8">mobilcom-debitel cloud app</a></figcaption></figure><p>It is a Google Chrome extension and can be installed via the Chrome Web Store. Once installed, any Android device you connect to your computer gets the app installed automatically. Afterwards the connected device’s screen will be shown in a Vysor window.</p><p>For improved logging you can use a small command line tool named <a href="https://github.com/JakeWharton/pidcat"><em>PID Cat</em></a><em>, </em>which is basically a color coded logcat. It is a python script, which you can install on macOS via homebrew (brew install pidcat), or manually set a path variable to the script. You only need to call pidcatwith your specific app package name to start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzkKnrylwJo6qKGRwq-X7w.png" /><figcaption><a href="https://github.com/JakeWharton/pidcat">PID Cat</a></figcaption></figure><p>One tool I frequently use is the Android Studio Plugin <a href="https://github.com/pbreault/adb-idea"><em>ADB Idea</em></a>.</p><p>It is a simple small pop-up which opens up when you type Ctrl+Shift+A (or Ctrl+Alt+Shift+A for Windows) to execute adb operations quickly. You can install it using the Android Studio plugin repository.</p><p>As you can see, the app is simple, but it has all the adb commands you need. In the latest version it also supports restarting the app with an attached debugger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*AOBqZpafW3xMIy1t." /><figcaption><a href="https://github.com/pbreault/adb-idea">ADB Idea</a></figcaption></figure><p>If you want to change certain app settings at runtime and start custom events you can use a very small nice tool named <a href="https://github.com/orhanobut/bee"><em>Bee</em></a>. The tool can be accessed via a floating button added to any Activity defined by the developer. By clicking on the bee button certain debug events can be fired, e.g. displaying a notification or changing some preference values. For installation you will need to add the dependency and call the <em>Bee</em> object with an activity context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*7I5CgYR2G1gg2l9Esr9F-g.png" /><figcaption><a href="https://github.com/orhanobut/bee">Bee</a></figcaption></figure><p>QA and software testing often involves testing REST API routes. One way to test how your app reacts to specific responses is to use a <em>mock server.</em> <em>Node.js</em> and the <a href="http://expressjs.com/"><em>express framework</em></a> are a very easy way to create a simple working API in no time. Here is an example for a simple API which returns a JSON file at a GET request:</p><pre>var fs = require(“fs”);<br>var express = require(“express”);<br>var app = express();<br>var port = app.get(“port”);<br></pre><pre>// Competition list<br>app.get(‘/competitions’, function(req, res) {<br>  res.type(‘application/json; charset-utf8’);<br>  res.status(200).send(fs.readFileSync(‘data/competitions.json’, ‘utf8’));<br>});</pre><pre>// Starting the server<br>app.listen(port, function() {<br>  console.log(‘Express server listening on port ‘ + port);<br>});</pre><p>If you like to go deeper into mock servers using express, have a look at <a href="http://expressjs.com/en/guide/routing.html"><em>node.js express dev guides</em></a>.</p><p>Another tip for testing purposes is the use of the <a href="https://play.google.com/store/apps/details?id=com.tspoon.androidtoolbelt&amp;hl=de"><em>Fill RAM</em></a> app, a small Android app to test your app against low memory and state issues that are common reasons for crashes. You simply open the app and start the ram filling task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*pt9vZonN3d5c_YQU." /><figcaption><a href="https://play.google.com/store/apps/details?id=com.tspoon.androidtoolbelt&amp;hl=de">Fill RAM app</a></figcaption></figure><p>Last but not least, the often forgotten <a href="https://developer.android.com/studio/profile/monitor.html"><em>Android Studio Monitor</em></a> provides useful information about the current memory status. Big humps in your memory usage can indicate memory leaks, significant deviations in your network usage may be pointers to caching problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KxpsSgJK9H3A1BcS." /><figcaption>Android Studio Monitor</figcaption></figure><p>This tool comes with Android Studio, just open the <em>Android Monitor</em> window at the bottom of your Android Studio IDE.</p><p>We have seen many general tools and recommendations for app development and analysis. In the next sections, we will discuss this in more detail.</p><h3>How to track down memory leaks easily</h3><p>Let us start with a nice small example of how to create a memory leak. Consider an activity which holds three fragments in a ViewPager (e. g. via a FragmentPagerAdapter). The ViewPager holds the two adjoining fragments in the cache, so all three fragments get loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*cqPAAG2wLiLfUiGz." /></figure><p>The top fragment here has a callback which needs the activity context for resource handling. Now let’s change the view to the bottom fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*E3C4apswXyJlVl3C." /></figure><p>The top fragment is no longer needed in the cache and the garbage collector should collect and clean the unneeded references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*OJWaAEeYuS-JT4N2." /></figure><p>The callback still holds the static reference to the activity context. And this creates the memory leak, the garbage collector can not clean up the top fragment and all of its resources, because it is still needed in the callback.</p><p>This memory leak can easily be solved via WeakReferences. <a href="https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8#.bmfwfx85v">For further reading regarding that topic please check this article from my co-worker</a> <a href="https://medium.com/u/c9426abb9b55">Johan Olsson</a>.</p><p>There are two easy ways to detect memory leaks. The first is to <em>analyze the Java heap via Android Studio</em>. If you remember the view of the Android Studio Memory Monitor, you can see five small buttons located below the <em>“Monitors”</em>-tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*FQKEkPAt61QgJwcP." /></figure><p>If you click on the <em>“dump java heap”</em>-button you will see that this button appears in the monitor progress view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*6kSYUpiFaWF-efH0." /></figure><p>After a short loading time a window appears. On the right side there is the tab named <em>“Analyzer Tasks”</em>, open it and perform the analysis via click on the play button.</p><p>If in the section <em>“Analysis Results”, </em>you see the bulletpoint <em>“Leaked Activities”</em> then — congratulations — you have found a memory leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*hq8IKOFjt5y7bQAE." /><figcaption>Found memory leak via java heap dump</figcaption></figure><p>There are other ways to detect memory leaks in your app, as well. One of them is a tool called <a href="https://github.com/square/leakcanary"><em>LeakCanary</em></a>, an Android library. To get started you add the dependencies into your debug builds and call the LeakCanary install factory method within your app context. If a memory leak is detected the user gets a notification. For more information please check the <a href="https://github.com/square/leakcanary/wiki/FAQ">FAQ</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*LdMcn57kYdbcfbW4SntQjQ.png" /><figcaption><a href="https://github.com/square/leakcanary">LeakCanary</a></figcaption></figure><p>These are just a few ways to detect possible memory leaks. However, you should not completely rely on the tools since not every memory leak may be detected. The best way to avoid memory leaks is to be aware of the consequences your code has. This can be achieved by studying how the overall memory architecture works in a computer and how Java incorporates it. After a while you should get a feeling for it.</p><p>This article shows many tips to improve your Android app, your workflow and how to detect memory leaks. In the second part of this article, I will introduce you to more analysis tools, technical debt identification und in-depth APK checking.</p><p>We have seen many tips to improve your Android app, your workflow and how to detect memory leaks. In the next part of this article we will get information concerning all kind of measurement tools, technical debt identification and APK analysis.</p><p>Don’t miss the next part and follow <a href="https://medium.com/freenet-engineering">freenet Engineering</a> for further Android App Development tips.</p><p>Update: You can find <a href="https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-2-ced14ec6740f#.nh2426l2r">Part 2 here</a>.</p><p><em>Interested in how we develop software? </em><a href="https://stellenangebote.freenet-group.de/stellenangebote.html?order[dir]=asc&amp;order[field]=stellenbezeichnung&amp;filter[countr][]=474&amp;filter[radius_search_location]=&amp;filter[radius_search_range]=25&amp;filter[aufgabengebiet_id][]=21&amp;filter[volltext]="><em>Join our team in Hamburg, Germany!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34415239e91a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/freenet-engineering/useful-tips-to-inspect-your-android-app-part-1-34415239e91a">Useful tips to inspect your Android app — Part 1</a> was originally published in <a href="https://medium.com/freenet-engineering">freenet Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory leaks in Android — identify, treat and avoid]]></title>
            <link>https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8?source=rss----3a7d5106526c---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0b1233acc8</guid>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Johan Olsson]]></dc:creator>
            <pubDate>Wed, 13 Apr 2016 13:25:00 GMT</pubDate>
            <atom:updated>2016-06-29T09:51:14.482Z</atom:updated>
            <content:encoded><![CDATA[<p>In our daily pursuit of building better apps, we as developers need to take many things into consideration in order to stay on track, one of which is to make sure that our apps do not crash. A common cause of crashes are memory leaks. This particular problem can manifest itself in various forms. In most cases we see a steady increase in memory usage until the app cannot allocate more resources and inevitably crashes. In Java this often results in an <strong>OutOfMemoryException</strong> being thrown. In some rare cases, leaked classes can even stick around for long enough to receive registered callbacks, causing some really strange bugs and all too often throw the notorious <strong>IllegalStateException</strong>.</p><p>To help others minimize time spent on code analysis I’ll present a few examples of memory leaks, how to identify them in Android Studio and most importantly how to remove them.</p><h4>Disclaimer</h4><p>The purpose of this post and its code examples is to promote a deeper understanding of memory management, especially in Java. The general architecture, management of threads and handling of running HTTP requests shown are not ideal for a production environment and merely serve as carrier of the point being made: Memory leaks in Android is a thing to be considered.</p><h4>Registering listeners</h4><p>This shouldn’t really be a problem but all too often I see calls to various register methods but their unregister counterparts are nowhere to be seen. This is a potential source of leaks, since these methods are clearly designed to be balanced off by each other. Without calling the unregister method, the instance will probably keep a reference around long after the referenced object has been terminated and will thus start leaking memory. In Android this is especially troublesome if that object is an activity, since they often hold a large amount of data. Let me show you what that might look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9e0ae113001d32c25a42cd878c6b2f/href">https://medium.com/media/0d9e0ae113001d32c25a42cd878c6b2f/href</a></iframe><p>In this example we’re letting the Android <a href="https://developer.android.com/reference/android/location/LocationManager.html"><strong>LocationManager</strong></a> inform us about location updates. All we need to set this up is the system service itself and a callback to receive the updates. Here we implement the location interface in the activity itself, meaning that the <strong>LocationManager</strong> will hold a reference to our activity. Now if the device were to be rotated, a new activity would be created replacing the old one already registered for location updates. Since a system service will most definitely outlive any activity, the <strong>LocationManager</strong> will still hold a reference to the previous activity, making it impossible for the garbage collector to reclaim the resources still tied to that particular activity, resulting in memory being leaked. Repeated rotation of the device will then cause non-reclaimable activities to fill up the memory, ultimately leading to an <strong>OutOfMemoryException</strong>.</p><p>But in order to fix a memory leak, we first have to be able to find it. Luckily <strong>Android Studio</strong> has a built in tool called <strong>Android Monitor</strong> we can use to observe memory usage among other things. All we really have to do is open the Android Monitor and go to the Monitors tab to see how much memory is used and allocated in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*3R36AJUjtdBArkIxPuED3g.png" /><figcaption>The Android Monitor in Android Studio 2.0</figcaption></figure><p>Any interactions causing resource allocation will be reflected here, making it an ideal place for keeping track of your application’s resource usage. In order to find our memory leak, we need to know what the memory contains at a point in time when we suspect that memory has been leaked. For this particular example, all we have to do is start our application, rotate the device once and then invoke the <strong>Dump Java Heap</strong> action (next to <strong>Memory</strong>, the third icon from the left). This will generate a <strong>hprof</strong> file, which contains a memory snapshot at the time we invoked the action. After a couple of seconds, Android Studio automatically opens up the file, giving us a neat visual representation of the memory for easy analysis.</p><p>I will not go into depth about how to navigate the huge memory heap. Instead I’ll direct your attention to the <strong>Analyzer Tasks</strong> in the upper right corner of the screenshot below. All you have to do to detect the memory leak introduced in the example above is to check <strong>Detect Leaked Activities</strong> and then press play to get the leaked activity to show up under <strong>Analysis Results</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lLq6rPP47zEODOePB8YCA.png" /><figcaption>Visualization of the Java Heap with the leaked activity highlighted</figcaption></figure><p>If we select the leaked activity we are presented with a <strong>Reference Tree</strong> where the reference that is keeping the activity alive can be identified. By looking for instances with depth zero we find that the instance <strong>mListener</strong> located within the location manager is the reason our activity can’t be garbage collected. Going back to our code we can see, that this reference is due to the <strong>requestLocationsUpdates</strong> where we set the activity as a callback for the location updates. Consulting the <a href="https://developer.android.com/reference/android/location/LocationManager.html">documentation on the location manager</a> it quickly becomes clear that in order to unset the reference we must simply call the <strong>removeUpdates</strong> method. In our example since we register for updates in the <strong>onCreate</strong> method, the obvious place to unregister would be in the <strong>onDestroy</strong> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8164802709759cefff60015449541e9c/href">https://medium.com/media/8164802709759cefff60015449541e9c/href</a></iframe><p>Rebuilding the application and performing the same memory analysis as above should result in no leaked activities regardless of how many times the device is rotated.</p><h4>Inner classes</h4><p>A very common data structure in Java is the so called inner classes. They are popular since they can be defined in such a way, that only the enclosing class can instantiate them. What many may not realize is the fact that these kind of classes will create an implicit reference to the enclosing class, which may not always be what you want. Unintentional referencing is very prone to errors, especially if the two classes have different life cycles. Consider the following common Android activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deb26c841966626420cbdf7baf68ebda/href">https://medium.com/media/deb26c841966626420cbdf7baf68ebda/href</a></iframe><p>This particular implementation will work just fine. The problem is that it will most definitely retain memory longer than necessary. Since the <strong>BackgroundTask</strong> keeps an implicit reference to the <strong>AsyncActivity</strong> while also running on another thread which lacks cancellation policy the activity will remain in memory with all of its resources attached until the background thread has terminated. In case of a HTTP request, this can take a long time, especially on a slow connection.</p><p>By performing the same steps as in the previous example, with the addition of ensuring a long running background task, we end up with the following analysis results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRS85Ed5t0q5DoeqhD8Qnw.png" /><figcaption>Visualization of the Java Heap with the retaining instance highlighted</figcaption></figure><p>As seen in the analysis above, the <strong>BackgroundTask</strong> is indeed the culprit behind this memory leak. First order of business is to eliminate the unintended reference to the activity by making the class static but by doing so we also cannot directly access the <strong>textView</strong> anymore. Therefore we also need to add a constructor in order to pass the view on to the task. Finally we need to introduce a cancellation policy for the task, which is described in the <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask documentation</a>. Taking all of that into account, let’s see what our code ends up like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e4b12c6612efe10578b0f4f585851b/href">https://medium.com/media/33e4b12c6612efe10578b0f4f585851b/href</a></iframe><p>Now that the implicit reference has been eliminated, we pass the single relevant instance to the task via the constructor. With our cancellation policy in place, let’s run the analyzer task once more to see if this change eliminated the memory leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U-vgoCbOR_EvmcSLfTUdQ.png" /><figcaption>Visualization of the Java Heap with the retaining instance highlighted</figcaption></figure><p>It seems we still have some work to do. By applying the same technique as in the last example we can identify the highlighted instance in the <strong>Reference Tree</strong> as the one keeping the activity alive. So what’s going on here? If we look closer at its parent node we see that the view has a reference to <strong>mContext</strong> which is nothing other then our leaked activity. So how to solve this? We can’t eliminate the context, to which the view is bound and we need the view reference in the <strong>BackgroundTask</strong> in order to update the UI. One simple way to solve this would be to use a <a href="https://developer.android.com/reference/java/lang/ref/WeakReference.html"><strong>WeakReference</strong></a>. Our reference to the <strong>resultTextView</strong> is considered strong and has the ability to keep the instance alive preventing garbage collection. In contrast, a <strong>WeakReference</strong> will not keep its referenced instance alive. As soon as the last strong reference to an instance has been removed, the garbage collector will reclaim its resources regardless of any weak references to this object. Here is what the final version will look like using WeakReference:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d6354b975d7b8aa3105d1f40ac8f31/href">https://medium.com/media/83d6354b975d7b8aa3105d1f40ac8f31/href</a></iframe><p>Notice that in <strong>onPostExecute</strong> we have to check for <strong>null</strong> to verify, if an instance has been reclaimed or not.</p><p>Finally, running the analyzer task once more will confirm that our activity is no longer being leaked!</p><h4>Anonymous classes</h4><p>These kinds of classes have the same disadvantages as the inner class, namely they hold a reference to the enclosing class. Just as inner classes, anonymous classes can be sources of memory leaks when passed to an instance that operates outside of the activity’s life cycle or performs work on another thread. For this example I’ll use the popular HTTP client <a href="http://square.github.io/retrofit/">Retrofit</a> to perform an API call and pass the response to a callback. The client is set up like the example on the <a href="http://square.github.io/retrofit/">Retrofit homepage</a>. I’ll also keep the reference to the <strong>GitHubService</strong> in the application instance, which is not a particular good design choice but serves the purpose of this example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f64084a7940dbf7eef9e38f925a0589/href">https://medium.com/media/8f64084a7940dbf7eef9e38f925a0589/href</a></iframe><p>This is a common type of solution and may not result in any leaks. But if we execute this on a slow connection the analyzer result will be different. Remember, the activity is kept until the thread has terminated, just as in the inner class example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KNoCC56GIeAByjKRlEjWw.png" /><figcaption>Visualization of the Java Heap with the retaining instance highlighted</figcaption></figure><p>Following the same line of reasoning as in the inner class example we arrive at the conclusion, that the anonymous callback class is the reason for our memory leak. However, just as the inner class example this code contains two problems. First of all, there is no cancelling policy for the request. Secondly, the implicit reference to the activity needs to be dissolved. Taking this into account an obvious solution would be to do the same thing we did in the inner class example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bad7c258aad1328b5ffbc76490740d32/href">https://medium.com/media/bad7c258aad1328b5ffbc76490740d32/href</a></iframe><p>Running the analyzer task on this solution will result in no leaked activities.</p><h4>Conclusion</h4><p>Background tasks running independently of the activity life cycle can be a hassle. Add to that the need to coordinate the flow of data between the UI and various background tasks and you have a recipe for disaster if you’re not careful. Be aware of what you’re doing and of the performance impact your code might have. A good start would be to consider these general guidelines when dealing with activities:</p><ul><li><strong>Favor static inner classes over non-static. </strong>Each non-static inner class will have an implicit reference to its outer class instance which may result in unwanted behaviors. Instead define these classes as static and store life cycle references needed as <strong>WeakReferences</strong>.</li><li><strong>Consider other means of background service.</strong> Android offers a wide variety of ways to get work off the main thread such as <strong>HandlerThread</strong>, <strong>IntentService</strong> and <strong>AsyncTask</strong>, each with their own strengths and weaknesses. In conjunction, Android offers several mechanisms to propagate information back to the main thread in order to update the UI. The <strong>BroadcastReceiver</strong> is one very capable tool to achieve this.</li><li><strong>Do not blindly rely on the garbage collector.</strong> When coding in a garbage collected language it’s easy to make the assumption, that memory management does not have to be taken into consideration. Our examples clearly show that this is not the case. Therefore, make sure that your allocated resources are all collected as expected.</li></ul><h4>Want to learn more?</h4><p>Are you just getting started with memory and performance management in Android? Then consider checking out the following resources for more information on how to build better apps and become a better Android developer.</p><ul><li><a href="https://www.youtube.com/playlist?list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE">Android Performance Patterns</a> on YouTube</li><li><a href="http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html">Avoiding memory leaks</a> from the Android Developer Blog</li><li><a href="https://github.com/square/leakcanary">LeakCanary</a> — A memory leak detection library for Android and Java</li></ul><p><strong>UPDATE:</strong> With the help of some friendly remarks from the <a href="https://www.reddit.com/r/androiddev/comments/4ps3p3/memory_leaks_in_android_identify_treat_and_avoid/">Android community</a> I’ve adjusted the example code to follow customary best practices.</p><p><em>Interested in how we develop software? </em><a href="https://stellenangebote.freenet-group.de/stellenangebote.html?order[dir]=asc&amp;order[field]=stellenbezeichnung&amp;filter[countr][]=474&amp;filter[radius_search_location]=&amp;filter[radius_search_range]=25&amp;filter[aufgabengebiet_id][]=21&amp;filter[volltext]="><em>Join our team in Hamburg, Germany!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b1233acc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/freenet-engineering/memory-leaks-in-android-identify-treat-and-avoid-d0b1233acc8">Memory leaks in Android — identify, treat and avoid</a> was originally published in <a href="https://medium.com/freenet-engineering">freenet Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>