<?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 Thiago Valle on Medium]]></title>
        <description><![CDATA[Stories by Thiago Valle on Medium]]></description>
        <link>https://medium.com/@thiagoqvalle?source=rss-7bb3e79cd84b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a_dv1qHPRtUvjQA0TN96-A.jpeg</url>
            <title>Stories by Thiago Valle on Medium</title>
            <link>https://medium.com/@thiagoqvalle?source=rss-7bb3e79cd84b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:46:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thiagoqvalle/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[An inner look into AsyncTask]]></title>
            <link>https://medium.com/@thiagoqvalle/an-inner-look-into-asynctask-7d87957941f3?source=rss-7bb3e79cd84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d87957941f3</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[asynctask]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Thiago Valle]]></dc:creator>
            <pubDate>Wed, 14 Jun 2017 18:59:51 GMT</pubDate>
            <atom:updated>2017-06-14T23:03:11.208Z</atom:updated>
            <content:encoded><![CDATA[<p>If we look into Android options on running background tasks we will often find blog posts, videos and references to AsyncTask as a possible solution. But if we read the Android documentation on it and on processes and threads, we will find little to no useful information on it. Yes, we might learn how to use it in our code and everything will work, however, most Android classes are quite complex even though they have a simple API. And the thing about threads/background operations in general is that they can’t be so easily abstracted, when this is done it usually hides important implementation details that in the end matter to us. AsyncTask is one of those cases and that’s why the documentation says things like:</p><blockquote>AsyncTasks should ideally be used for short operations (a few seconds at the most.)</blockquote><p>Yes, ok, but… why?</p><p>In this article I’ll try to explain the inner works of AsyncTask so that we understand how it works, when to use it and when to avoid it.</p><h3>First things first</h3><p>In order to understand AsyncTask, let’s look first how to use it.</p><p>AsyncTask purpose is to make it easy to run tasks outside the UI thread, it does this by providing you with a relatively simple easy to use interface consisting of these methods:</p><p>onPreExecute</p><p>doInBackground</p><p>onProgressUpdate</p><p>onPostExecute</p><p>You use them by extending the AsyncTask class, implementing these methods and then calling execute on the UI Thread. What will happen is:</p><p>AsyncTask will call onPreExecute in the UI Thread so that you can do some work before it starts doing background work, this is usually setup code. After that your code in doInBackground will start executing and do whatever time consuming code that you desire, meanwhile in the UI thread onProgressUpdate can be called to update to the user that the background task is running, this will only be called if inside doInBackground you called publishProgress, since you’re displaying some progress to the user this will be called on the UI Thread. Also on the UI thread after everything ends you will get a call to onPostExecute with the final data that you processed.</p><p>So the idea is:</p><ul><li>Do some setup</li><li>Define what you want to execute in background (and if you have any progress call publishProgress)</li><li>Update to the user on how everything is doing</li><li>When everything is done: onPostExecute</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*tHAukxdQBloBB2YEwezRQg.png" /><figcaption>AsyncTask execution model</figcaption></figure><h3>What’s happening on the inside?</h3><p>The thing about AsyncTask are the consequences of how it works internally. Let’s look first at what execute() does.</p><p>If we look at the code of this method, we’ll see that inside it just has one line:</p><pre><strong>return </strong>executeOnExecutor(sDefaultExecutor, params);</pre><p>What this does is it uses another method of AsyncTask which is executeOnExecutor, which means that AsyncTask doesn’t just spawn a simple Thread and run our code there, it uses the <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html">Java Executor Framework</a> to create a thread pool and let it control how and when our code is run. The executor that execute() passes to executeOnExecutor() is called sDefaultExecutor and is declared as a static Executor, this is important for us because it means that Application wise if we call execute() we’ll be using the same executor, and if we look at how this executor is implemented we’ll see that it has a queue which only let’s one Task run at a time.</p><p>So resuming: execute() calls executeOnExecutor() and we get a queue of tasks that wait for execution while just one Task is running in the executor, all of this applicationwise. This means that even though we call 10 AsyncTasks execute() one will be executing while the others will all be enqueued.</p><p>We can call executeOnExecutor() directly and use the static AsyncTask.THREAD_POOL_EXECUTOR to run tasks in parallel, if we do that and have some shared data in our tasks we’ll have to synchronize it ourselves since AsyncTask can’t garantee thread safeness for us. Aside from that, when we publish the result to the UI Thread even if we are running several tasks in parallel it will get on a queue again, the UI Thread queue. When we call publishProgress() it does this</p><pre><strong>if </strong>(!isCancelled()) {<br>    <em>getHandler</em>().obtainMessage(<strong><em>MESSAGE_POST_PROGRESS</em></strong>,<br>            <strong>new </strong>AsyncTaskResult&lt;Progress&gt;(<strong>this</strong>, values)).sendToTarget();<br>}</pre><p>What it does is it uses the UI Thread Handler to send our message to the UI Thread, and as we know the UI thread has a queue to receive messages as well, this is the way that Android synchronizes information and guarantee thread safeness. This is not a problem per se since our tasks would be running any time consuming work in the background in parallel, but we must be aware of how AsyncTask updates the UI Thread.</p><h3>Consequences of this model of execution</h3><p>As I mentioned, the first thing you must be aware is that if your achitecture rely on AsyncTask to do all your background work and you use execute, every task will be queued in your app. You can use a custom executor, but if you have shared data it’s easier to probably change your whole architecture to use other background execution classes or an external library.</p><p>One other issue with AsyncTask is when it’s used as an inner class. If you do this Java will give your class an implicit reference to the outer class, and if your outer class is an Activity what will happen is: everytime there is a configuration change you will have two activities in the memory, the new one and the older one(the outer reference) that can’t be destroyed by the garbage collector. Since active threads are considered GC roots they can’t be destroyed, so your memory will pratically be doubled as long as your AsyncTask is running with the reference of the older activity.</p><p>One solution would be to make an inner static class because it references the global class object and not your outer class directly, another solution would be to separate the AsyncTask in other class altogether. But even with these solutions you will still have to reference the outer activity to send messages to it, so on any context switch you will have to get the reference of the new activity and pass to the AsyncTask. A better solution would be to use <a href="https://developer.android.com/reference/java/lang/ref/WeakReference.html">WeakReferences</a>.</p><h3>AsyncTask is a “threading primitive”</h3><p>Google sometimes uses the terminology: threading primitives. What they mean is they have many solutions to do background work in your app and you must understand the inner work of them all so that you can use what’s best for each scenario. AsyncTask is one of these primitives and is only best used when you have some simple UI task that you’ll have some sort of guarantee that it won’t take long. I hope this article showed why this is and that it motivates you to look at the source code of other classes to understand the whys and how to better use them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d87957941f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git cookbook]]></title>
            <link>https://medium.com/@thiagoqvalle/git-cookbook-52e2b301187e?source=rss-7bb3e79cd84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/52e2b301187e</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Thiago Valle]]></dc:creator>
            <pubDate>Thu, 11 May 2017 17:52:55 GMT</pubDate>
            <atom:updated>2017-05-11T17:52:55.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Git is a really neat tool, over the years using it I’ve recurrently found myself in a situation and often forgetting what I did to solve it the last time. I usually remembered the logic behind it but didn’t remember the commands, so in order to help me I started writing the commands on my git cookbook. Here you go:</p><h4>Show a file in the state it was in a commit</h4><p>git show <em>commitsha</em>:<em>path-to-file</em></p><h4>Fetching from all remotes</h4><p>git remote update</p><h4>Listing info from remote</h4><p>git remote show <em>remotename</em></p><h4>List the files of a commit</h4><p>git diff-tree --no-commit-id --name-only -r <em>commitsha</em></p><h4>Rename a branch</h4><p>git branch -m <em>o</em>ldname <em>newname</em></p><h4>Undoing all changes in unstaged area</h4><p>I used to do git reset --hard HEAD a lot but it’s better to do git checkout -- . since it doesn’t mess with your git history</p><h4>Editing a specific commit</h4><p>git rebase -i <em>commitsha</em>^ and then choose to edit the commit you want and pick the others, follow the instructions to ammend and commit</p><h4>Apply a commit from another branch</h4><p>git cherry-pick <em>commitsha</em></p><h3>Log</h3><h4>Last n commits</h4><p>git log -<em>n</em></p><h4>Making it pretty</h4><p>git log --oneline <br>git log --decorate<br>git log --graph<br>These can be combined and some accept parameters</p><h4>Filtering</h4><p>by author: git log --author=<em>name</em><br>by date: git log --after=<em>date</em><br>by file: git log -- <em>file</em><br>by range: git log <em>commitsha-from</em>..<em>commitsha-to</em></p><h3>Reflog</h3><h4>Recover deleted branch</h4><p>git reflog and find the sha of the state before the deletion<br>git checkout -b <em>sha</em></p><h4>Go back to a specific state</h4><p>git reflog and find the sha<br>git reset --hard <em>sha</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52e2b301187e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android automated bisecting]]></title>
            <link>https://medium.com/@thiagoqvalle/android-automated-bisecting-2f918e6830bb?source=rss-7bb3e79cd84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f918e6830bb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[bisect]]></category>
            <dc:creator><![CDATA[Thiago Valle]]></dc:creator>
            <pubDate>Sun, 26 Feb 2017 15:18:46 GMT</pubDate>
            <atom:updated>2017-02-26T16:11:41.616Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m currently working on a project where our team needs to find out exactly where a given bug was introduced in our codebase. Given that it’s a tedious and time consuming process we decided to automate it. Here is a brief explanation on how one can do it.</p><h3>Git bisect is your best friend</h3><p>The main idea is using a git command called bisect, it performs a binary search between commits to find the bug. How git bisect works is you define a bad commit and a good commit, these are reference points for git to know when the code was working and when it stopped working. Git will then pick the commit in the middle between these two points, you will then tell git if the commit that it selected is a good or a bad one, based on what you tell git it will then divide by two again until it finds the faulty commit. <a href="https://git-scm.com/docs/git-bisect">Here</a> is a better explanation.</p><p>Obviously we don’t want to manually say that the checked out commit is a good or a bad one, git bisect takes care of this for us as well. We can specify a command or a script to run every time, and based on the exit code it will decide what to do.</p><pre>git bisect run <em>command arguments</em></pre><p>When git checks out a commit it will run the command and if the exit code is 0 it will decide that it’s a good commit. If it’s 1 through 127 it will decide that it’s a bad commit, except for 125 which is reserved for when something goes wrong but it’s not related to what you’re looking, such as a broken build.</p><h3>If you’re not testing you should be testing</h3><p>Ok, git will take care for us of checking commits out and finding the culprit, but we still need to automate the part where we decide if there is a bug or not. If we were doing this manually we would be doing something like the following:</p><ul><li>Building the app</li><li>Installing the app</li><li>Opening some activity</li><li>Making some actions</li><li>Checking if the bug exists or not</li></ul><p>Luckily for us this sounds a lot like what <a href="https://google.github.io/android-testing-support-library/docs/espresso/">espresso</a> does. So yes, the idea is each time git checks out a commit we run a test and based on our assertions it will decide if the bug exists or not.</p><p>The perfect case here is if from the beginning you already had a test that could be used to verify the behavior that the bug is causing. If not, before starting the bisect you can write a test <strong>and not commit it. </strong>It’s important to leave it unstaged so that when git starts checking out commits it can “transfer” it around.</p><h3>adb, gradle or custom script?</h3><p>So now we have the git bisect and the test that will verify the bug, we only need a way to tell git to run the test in the command part of bisect.</p><p>Since I’m very fond of adb I initially tried to use it to automate things, but unfortunately things are a little bit tricky here. When you use adb shell it actually returns the exit code of what you’re running, however, to run instrumentation tests one would use adb shell am instrumentation but am doesn’t seem to return exit codes based on the results of the tests, which sucks for us. Aside from that there’s still the part of building and installing the app(both the main app and the instrumentation one), so adb was a no go.</p><p>Gradle on the other hand exits with the right code and takes care of building and installing our app, which is nice. Gradle can also run only a single instrumentation test:</p><pre>gradlew app:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.yourpackage.app.YourClass#yourMethod</pre><p>In theory you could use gradlew cAT --tests *.yourMethod but the --tests parameter doesn’t seem to be working right now. So we use the -Pandroid.testInstrumentationRunnerArguments which passes arguments to the instrumentation runner(much like we do in adb). <a href="https://github.com/googlesamples/android-testing-templates/tree/master/AndroidTestingBlueprint">Here</a> is a more in-depth explanation on how this works.</p><p>The final command when starting the bisect would be:</p><pre>git bisect run ./gradlew app:connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.yourpackage.app.YourClass#yourMethod</pre><p>This will suffice for most cases, the only problem is Gradle returns 1 both when the test doesn’t pass and when the build breaks. Sometimes this can be an issue, sometimes not, depending on how many broken commits you have git will get lost or choose the wrong commit. But sometimes even with a broken build it can find the c0mmit which introduced the bug.</p><p>My recommendation in this case, and in cases with more specific requirements, is to write a script which handles these kinds of things for you and properly return the right exit code, this way you will always guarantee the result of git bisect.</p><h3>Conclusion</h3><p>So here you go: git + espresso + gradle = great success. The main idea is automating the git bisect for us, you don’t need to use espresso but it’s the easier way to go. If you have a complicated requirement probably scripting with adb and something like UI Automator will do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f918e6830bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introdução ao adb]]></title>
            <link>https://medium.com/@thiagoqvalle/introdu%C3%A7%C3%A3o-ao-adb-4b745918c05a?source=rss-7bb3e79cd84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b745918c05a</guid>
            <category><![CDATA[android-debug-bridge]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[adb]]></category>
            <dc:creator><![CDATA[Thiago Valle]]></dc:creator>
            <pubDate>Tue, 31 Jan 2017 18:16:54 GMT</pubDate>
            <atom:updated>2017-01-31T18:16:54.103Z</atom:updated>
            <content:encoded><![CDATA[<p>Existem ferramentas dentro do SDK do Android úteis para desenvolvedores, uma delas é o adb. O Android Debug Bridge é uma ferramenta de linha de comando que permite que você se conecte com um emulador ou dispositivo através do computador e faça ações como copiar arquivos, listar e debugar apps, etc. Acabamos usando o adb sem perceber pois o Android Studio o utiliza em background, porém quando precisamos de um controle maior como iniciar activities explicitamente, finalizar processos, ou quando precisamos que algo seja feito mais rápido é quando vamos para linha de comando e usamos ele diretamente.</p><p>Muitos dos comandos descritos aqui não farão sentido inicialmente e será difícil lembrar algumas coisas no começo. Isso é normal, a ideia aqui é apresentar como funciona o adb e o processo de aprendizado é exploratório. O importante é entender o que o adb é capaz de fazer e naturalmente toda vez que um problema aparecer você terá como saber se é possível(e se vale a pena) fazer com o adb, independente se você já tenha decorado os comandos ou não.</p><p>Para que o adb possa conectar com o seu dispositivo é necessário ativar a <strong>depuração usb </strong>nas<strong> opções de desenvolvedor. </strong>Além disso é importante adicionar ele no seu path para que possa ser usado de qualquer canto do seu terminal. O <a href="https://developer.android.com/studio/command-line/adb.html">manual</a> do adb explica melhor como fazer as duas coisas.</p><h3>Listando dispositivos</h3><p>Pra começar precisamos listar os dispositivos que estão conectados ao computador, para isso usamos:</p><pre>adb devices</pre><p>Esse comando lista todos os dispositivos que o adb consegue enxergar. Um exemplo comum é ter o celular carregando no computador e um emulador aberto, nesse caso apareceria algo do tipo:</p><pre>List of devices attached<br>066aacd10063afe9 device<br>emulator-5554 device</pre><p>No caso ele achou um emulador(emulator-5554) e um dispositivo físico(066aacd10063afe9), esse comando é formatado da seguinte maneira: número-de-série estado, onde número de série é uma string criada pelo adb pra identificar unicamente o dispositivo. E o estado é um dos três casos: device offline no device.</p><h3>Escolhendo um device</h3><p>Antes de mandar um comando para o adb precisamos falar para o adb qual dispositivo iremos usar.</p><p>Usamos adb <strong>-e</strong> comando para escolher o emulador e adb <strong>-d</strong> comando para escolher o dispositivo físico. Nos casos onde você precisa especificar qual dos androids conectados você quer mandar um comando, é usadoadb <strong>-s serial</strong> comando. No meu exemplo eu poderia fazer:</p><p>adb <strong>-s 066aacd10063afe9</strong> shell para abrir um shell com o meu celular.</p><h3>Comandos comuns</h3><h4>Copiando arquivos</h4><p>adb <strong>pull</strong> remoto local baixa arquivos do dispositivo para o computador.<br>adb <strong>push</strong> local remoto envia arquivos do computador para o dispositivo.</p><p>Para por exemplo copiar uma foto da pasta de <strong>downloads</strong> do Android para a pasta local <strong>/home/eu/Pictures </strong>do meu computador<strong>, </strong>fariamos:</p><pre>adb <strong>pull </strong>/sdcard/0/Downloads/foto.png /home/eu/Pictures</pre><h4>Instalando/Desinstalando apks</h4><p>adb <strong>install</strong> caminho_arquivo.apk instala um apk no dispositivo. Exemplo:</p><pre>adb <strong>install</strong> /home/eu/meuapp.apk </pre><p>Irá instalar o apk no celular, se ele já existe é preciso passar a flag -r para sobreescrever a instalação já existente: adb install<strong> -r</strong> /home/eu/meuapp.apk</p><p>adb <strong>uninstall</strong> com.my.package desinstala o app correspondente ao package no celular.</p><h4>Logcat</h4><p>O logcat é uma ferramenta que mostra logs do sistema, ela é importante para desenvolvedores pois os stack traces e informações de debug que desejamos ler aparecem lá. O Android Studio conecta com o logcat também e geralmente é mais comodo usa-lo via Android Studio, mas as vezes precisamos depurar erros em celulares remotos ou quando estamos em computadores que não tem o Android Studio instalado(como servidores de integração contínua).</p><p>O comando adb logcat roda o logcat no celular e imprime o log no terminal do computador. Para saber mais acesse o <a href="https://developer.android.com/studio/command-line/logcat.html">manual</a> do logcat.</p><h3>Shell</h3><p>O Android é um sistema operacional que roda em cima do kernel do linux. Isso nos traz algumas vantagens como por exemplo um shell que já é familiar pra quem usa linux. Existem duas maneiras de acessar o shell do Android via adb.</p><p>adb shell comando irá rodar o comando no shell do Android e voltar para o computador<br>adb shell irá entrar em um shell remoto no Android</p><p>ex: adb shell ls irá listar o diretório atual do celular.</p><p>Como o Android é baseado em linux podemos fazer várias coisas que também podemos em um linux como por exemplo adb shell ps para listar os processos rodando atualmente no celular(é interessante rodar isso e ver a ordem com que os processos são inicializados no Android). Alguns programas que comumente vem no linux já existem no Android mas outros são especificos do Android, para listar quais programas estão presentes podemos fazer:</p><pre>adb shell ls /system/bin</pre><p>Para desenvolvedores alguns programas chamam a atenção e são específicos do Android, é bom explorar os comandos e ir atrás na documentação pra ver o que cada um faz, iremos aqui explorar dois: pm, am.</p><h4>Package Manager</h4><p>Se você rodar o comando que lista os programas existentes dentro de /system/bin verá que existe um chamado pm. O Package Manager é um utilitário que gerencia os pacotes instalados no Android. Comandos comuns do package manager são esses:</p><p>pm list packages — lista os pacotes instalados no celular<br>pm list permissions — lista as permissões conhecidas<br>pm path pacote — exibe o caminho para o pacote passado como parâmetro<br>pm clear pacote — apaga os dados associados a um pacote<br>pm grant pacote permissão — concede uma permissão a um aplicativo<br>pm revoke permissão pacote — revoga uma permissão de um aplicativo</p><h4>Activity Manager</h4><p>Outra ferramenta útil disponível em /system/bin é uma ferramenta chamada am. O Activity Manager lida com activities, como por exemplo iniciar/parar activies, disparar intents, parar apps, etc.</p><p>am start intent — Inicia uma Activity relacionada ao intent.<br>am startservice intent — Inicia o service relecionado ao intent.<br>am force-stop package — Para tudo relacionado ao package.</p><h3>Explorar!</h3><p>É importante rodar os comandos e ver o que acontece, muitas vezes se não passamos paramêtros eles exibem um help com todas as opções possíveis. Usando o adb começamos a entender melhor como o Android funciona internamente, como dito acima toda vez que um problema aparece é bom pararmos para pensar se há uma chance de usar o adb ou não, isso acaba nos tornando melhores desenvolvedores indiretamente.</p><p>Para mais informações sobre o adb veja o <a href="https://developer.android.com/studio/command-line/adb.html">manual</a>. Lá é explicado em mais detalhes como ele funciona e alguns comandos a mais.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b745918c05a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>