<?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 Idan Damri on Medium]]></title>
        <description><![CDATA[Stories by Idan Damri on Medium]]></description>
        <link>https://medium.com/@idandamri?source=rss-5212cf59fc95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y3MEVb1F5DQbN5u4wEDjSQ.png</url>
            <title>Stories by Idan Damri on Medium</title>
            <link>https://medium.com/@idandamri?source=rss-5212cf59fc95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:07:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idandamri/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[Introduction to Android Studios Network Inspector traffic interception tool AKA “Rule”]]></title>
            <link>https://medium.com/@idandamri/introduction-to-android-studios-network-inspector-traffic-interception-tool-aka-rule-ff8cb8998c41?source=rss-5212cf59fc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff8cb8998c41</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flamingo]]></category>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Idan Damri]]></dc:creator>
            <pubDate>Fri, 05 May 2023 17:20:41 GMT</pubDate>
            <atom:updated>2023-05-05T17:38:10.293Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR — we can now capture requests/responses and modify the responses sent to our apps when connected to Android Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jg6Ni3B65dUUNNqxkmckEA.png" /></figure><p>Long have I waited for Android Studios’ “Flamingo” stable beta version to come out so I can try and play with this anticipated feature. Until now I could “sniff” requests/responses being sent and responses retrieved to my app through Android Studios’ “Network Inspector” or another app that works the same like <strong><em>Charles</em></strong>, <strong><em>Proxyman</em></strong>, etc. However, if I wanted to alter the responses I’ve received I had to use some other 3rd party app. In the last year, I have used 3rd party apps like the ones I’ve mentioned in order to analyze requests and even alter responses which is fun but I couldn’t wait for it to be a part of this great IDE (as I consider it should be).</p><p>In this article, we are going to explore this feature. In order to do so, I created a really simple app using Compose and Volly just to test it. I created a screen that has a single Text composable view and two composable Card views as buttons, one for sending a request and the other to reset the text.</p><blockquote>For the sake of this article, I used <a href="http://mockable.io/">Mockable.io</a> to create the simple Json for my request.</blockquote><ul><li>The first button sends a request to the <a href="https://demo2803075.mockable.io/flamingo_test">#link</a></li><li>The second button resets the text to “Hello Android!”</li></ul><p>You can check the app code at the following repo:</p><p><a href="https://github.com/idandamri/android_flamingo_test_app/tree/main">GitHub - idandamri/android_flamingo_test_app: A simple and small app in order to use the new &quot;Rule&quot; feature of Android Studio&#39;s Network Inspection tool</a></p><h3>So what does the app do?</h3><p><strong>When the request button was clicked:</strong></p><ul><li>A request is being sent By <a href="https://google.github.io/volley/"><em>Volley</em></a>.</li><li>If the <em>Volley</em> response fails the Composable Text will show “<em>Error</em>”.</li><li>If the response returns successfully it is being parsed. From the parsed data we search the key “name” and take its value to replace the text inside the Composable Text.</li><li>If everything runs well until this point we will see the text changed to “Hey Boss!”.</li><li>if the “Reset” is being clicked the value of the text will set the composable Text to “Hello Android!”.</li></ul><h3>And now to the point</h3><blockquote>I will not elaborate on the network inspector, I’ll jump to the “Rule” feature.</blockquote><p>In order to set the rule we need to open the app inspector tool from the “<em>View</em>” -&gt; “<em>Tool Window</em>” -&gt; “<em>App Inspection</em>”. Another way is clicking on “<em>App inspection</em>” in the bottom toolbar, like the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*uRFn40rPVrHozh08cz6iXw.png" /><figcaption>App inspection</figcaption></figure><p>When the app inspection is open make sure <strong>your process</strong> is selected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*HKj4diQiMwRg9vxGCLWtJQ.png" /><figcaption>This shows all processes open on your device — be sure to select your app&#39;s process</figcaption></figure><p>The next step is selecting the <em>Network Inspector</em> inside the <em>App inspection</em>, now it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFTjUH4pk6nDps-oPUYuoA.png" /></figure><p>Now select the “Rule” tab from the middle toolbar and click on the plus sign (<em>+</em>). Inside the rule details select HTTP/HTTPS, and fill in the HostURL, Path, Method, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwLvRP0YcPXecW4oZtrpzg.png" /><figcaption>Fill the rule according to your needs</figcaption></figure><p>My goal was to change the value that is returned to me from the server (reminder — “Hey Boss!”) into something else, in my case “Hey Man!”. In order to do so click on the plus (+) sign on the <em>body</em><strong><em> </em></strong>section. You can select how to use it, for the simplicity of it I replaced the whole body. It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyYIVg_BYokrExTrlx-0IA.png" /></figure><p>When you save it it will look in the “<em>Rule</em>” like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIgv2P4OsGjlFsgMWkZw9g.png" /></figure><p>Now if we click on the “Get Request” button, Android Studio will override the response gotten from the server and replace it with my response. Now we see that the Composable Text is set as we put it inside the Rule — “<em>Hey Man!</em>”.</p><p>I’m adding a short video for you to see how it will look fluently:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPDgmvcNzCfk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPDgmvcNzCfk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPDgmvcNzCfk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8cafec45a1b98d5ade9ba6cca5bed43/href">https://medium.com/media/b8cafec45a1b98d5ade9ba6cca5bed43/href</a></iframe><h3>Wrapping things up</h3><p>I think this is a great starting point for Android Studio, however, I hope that Google and the Android Studio team will add the following features on the next Android Studios versions:</p><ol><li>An option for editing a response we get and is monitored on the <em>Network inspection</em> so we will not have to edit <strong>manually</strong> all of the parts ourselves (this feature already exists in Charles/Proxyman, etc).</li><li>Adding <strong>Breakpoint</strong> for changing and editing live responses.</li><li>Adding a local file of a JSON as a response so you can transfer files of “server content” between colleagues (other known as <strong><em>Map Local/Remote</em></strong>)</li></ol><p>Thanks for reading, I hope this excites you as it excited me.<br>Enjoy playing with this great feature yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff8cb8998c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App links and Deep links with Android 12]]></title>
            <link>https://medium.com/@idandamri/app-links-and-deep-links-with-android-12-765cf9bc9cca?source=rss-5212cf59fc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/765cf9bc9cca</guid>
            <category><![CDATA[deep-links-android]]></category>
            <category><![CDATA[android-12]]></category>
            <category><![CDATA[android-app-linking]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Idan Damri]]></dc:creator>
            <pubDate>Fri, 18 Mar 2022 10:04:10 GMT</pubDate>
            <atom:updated>2022-04-04T07:26:20.119Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m_pJ3q8cgXFJlNCHbiOYTg.png" /><figcaption>Android cool icon image is taken from <a href="https://www.freeiconspng.com/img/3085">https://www.freeiconspng.com/img/3085</a></figcaption></figure><p><strong>Deep links</strong> — if you are familiar with the concept feel free to jump over to the headline of <strong>implementing Deep links with Android 12</strong>. For those of you who don’t know what is Deep Link, let’s elaborate a bit on that:</p><p><strong><em>According to Google:</em></strong></p><p><a href="https://developer.android.com/guide/navigation/navigation-deep-link">https://developer.android.com/guide/navigation/navigation-deep-link</a></p><blockquote>In Android, a deep link is a link that takes you directly to a specific destination within an app.</blockquote><p>As we can understand we can use Deep links as part of our navigation with the app. If the user has the app installed, it will be recognized by the app and navigate according to the implementation, if not - it is really based on how our Deep link is used (HTTP/HTTPS/customed scheme) - navigate to a browser/Play Store.</p><p>If you haven’t used or implemented a Deep Link in your app I suggest reading the following guide hand in hand with the link I added above (<a href="https://developer.android.com/guide/navigation/navigation-deep-link">googles android developer link</a>) and implementing it — there is no better way to learn it other than coding and testing it!</p><p><a href="https://medium.com/@muratcanbur/intro-to-deep-linking-on-android-1b9fe9e38abd">Intro to Deep Linking on Android</a></p><h3>Let’s talk business</h3><p>I am now in a position as a mobile team leader(I arrived not long ago) for a company that has 2 major apps, both apps&#39; navigation is used a lot with Deep links, Bussines-wise the customer wanted a link that can take a user directly to any flow inside the app with fewer clicks as possible through whatever promotion is used.</p><p>The older and more used app is running in both android and apple stores since 2011. Our navigation as I mentioned is mainly Deep links based and in use for a long time. Since Android 12 has been actively spread through main devices (Samsung, Xiaomi, Huawei, and more) we started seeing feedback on navigation issues, partly from the testers and partly from customers.</p><p>It took a while to understand that this issue is related to android 12. Once I understood it I started researching what can be the issue. I understood that the main issue in our app is with the deep links in android 12 more specifically <strong>App links with Android 12</strong>.</p><h4><strong>A short explanation of the differences:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L4vZ0ITT2ZMz1nVS.png" /></figure><p>In our company we use App links (HTTP/HTTPS schemes) because if the app doesn’t exist we would like to direct the user to <strong>our company&#39;s website</strong>, if the app exists (Android or iOS) it will open the app and navigate directly to the beginning of the flow. <strong>The problem with android 12 and unverified App links was that if the app was installed on the Android device it navigated to the Play Store rather than opening the app at the correct Activity and flow</strong>.</p><p>After some more reading and <em>googling</em> my problem was that the app links were not verified, so I followed the following guide by Android:</p><p><a href="https://developer.android.com/training/app-links/verify-site-associations">https://developer.android.com/training/app-links/verify-site-associations</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQkksEGbn9YEJKJbF31%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQkksEGbn9YEJKJbF31%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZXhyZjY5bTJvdWc2c2piZXdreWs1cmJiZG82c21pejFoNTg0YmQ0YiZlcD12MV9naWZzX2dpZklkJmN0PWc%2FQkksEGbn9YEJKJbF31%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="311" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0049d110c8a889420fe2365d0802e22/href">https://medium.com/media/e0049d110c8a889420fe2365d0802e22/href</a></iframe><p>According to them, I needed to create something called an “assetlinks.json” file. There are some ways to create it, I did it in the easiest way there is — just go to your play-console, search for the setup menu on the left, and select “App integrity”, then in the tabs click on “App signing” (If you didn’t go through the app signing process before and enrolled — I super suggest you do it and soon, more about it in the <a href="https://play.google.com/console/about/keymanagement/">link</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*zKhHLi8pvYno7MP65m8Q_w.png" /></figure><p>Now scroll down until you see “<strong><em>Digital Asset Links JSON</em></strong>”, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e44eEbZNrhIO3qLIfl6BIw.png" /><figcaption><strong><em>Digital Asset Links JSON</em></strong></figcaption></figure><p>You can copy it all by clicking on the <em>copy to clipboard</em> icon on the top right corner. After copying it to the clipboard, use any online JSON file creator like <a href="https://jsoneditoronline.org/#left=local.jenaca&amp;right=local.velahu">this</a> and download it and name it “assetlinks.json”.</p><p>Once it’s saved on your computer you’ll need to upload it to: <a href="https://domain.name/.well-known/assetlinks.json">https://<strong><em>domain.name</em></strong>/.well-known/assetlinks.json</a></p><p>So google’s mechanism can download it from this link. Here is an example for <a href="https://www.wikipedia.org/.well-known/assetlinks.json"><em>Wikipedia’s assetlinks.json</em></a><em>.</em></p><p>If you did everything right you can use the following Asset links testers tool and test it:</p><p><a href="https://developers.google.com/digital-asset-links/tools/generator">https://developers.google.com/digital-asset-links/tools/generator</a></p><p>For example, if we use <a href="https://www.wikipedia.org/.well-known/assetlinks.json"><em>Wikipedia’s assetlinks.json</em></a><em> </em>we can test it through the <strong><em>Asset links testers tool</em></strong> I showed you and we will see the following process succeded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJtaG9bqLM5QSf0Y4VhCRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QP02OdAjkszrfXuQQwFGKg.png" /></figure><p>There is another way to verify that the file is correct, Google provides a Digital Asset Links API to verify the accuracy of the assetlinks.json file:</p><blockquote><a href="https://digitalassetlinks.googleapis.com/v1/statements:list?%20source.web.site=https://domain.name:optional_port&amp;relation=delegate_permission/common.handle_all_urls">https://digitalassetlinks.googleapis.com/v1/statements:list? source.web.site=</a><strong>&lt;https://domain.name:optional_port&gt;</strong>&amp;relation=delegate_permission/common.handle_all_urls</blockquote><blockquote><strong>As a practical example, here is DoorDash’s link:</strong></blockquote><blockquote><a href="https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=https://www.doordash.com&amp;relation=delegate_permission/common.handle_all_urls">https://digitalassetlinks.googleapis.com/v1/statements:list?source.web.site=<strong>https://www.doordash.com</strong>&amp;relation=delegate_permission/common.handle_all_urls</a></blockquote><blockquote>If all goes well, the API will respond with the following:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*cqnOz0uzw6a4kR07.png" /><figcaption><strong>Michael Yotive Doordash&#39;s article</strong></figcaption></figure><p>I had one more issue here — when using the verify tool I got an error that my file’s content type wasn’t right and it had to be “<strong><em>Content-Type: application/json</em></strong>”. Learn from my mistake 😜</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZtzt8zhmmpVPUiSNMX%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZtzt8zhmmpVPUiSNMX%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZtzt8zhmmpVPUiSNMX%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/a44a7595644fcf0bce0ec88296071021/href">https://medium.com/media/a44a7595644fcf0bce0ec88296071021/href</a></iframe><p>Thanks a lot for taking the time to read this, I hope the article was helpful. See you guys next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765cf9bc9cca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AsyncTask is deprecated, now what? —  part 2]]></title>
            <link>https://medium.com/swlh/asynctask-is-deprecated-now-what-part-2-c094b60473dc?source=rss-5212cf59fc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/c094b60473dc</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[asynctask]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Idan Damri]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 13:42:49 GMT</pubDate>
            <atom:updated>2020-10-18T09:54:53.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>AsyncTask is deprecated, now what? — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tUf6rMSJCB9-nkQLE-xAw.jpeg" /></figure><p>So for those of you that followed me, I showed you a way to <a href="https://medium.com/swlh/asynctask-is-deprecated-now-what-f30c31362761">replace AsyncTask</a> with Runnables in Java. At the end of the article, I suggested a to work with Rx java or coroutines before working with the solution I showed, which was kind of a band-aid solution because of demands at that time. Now I am going to give you the way to handle the same process of replacing AsyncTask with coroutines.</p><p>For the sake of understanding, I am going to use the same example a snippet from the last article I wrote that is the AsyncTask I want to replace:</p><pre>public class myAsyncTask extends AsyncTask&lt;Void, Void, String&gt; {<br><br>    WeakReference&lt;myInteface&gt; myIntefaceWeakReference;<br><br>    public myAsyncTask(myInteface listener) {<br>        this.myIntefaceWeakReference = new WeakReference&lt;&gt;(listener);<br>    }<br><br>    @Override<br>    protected void onPreExecute() {<br>        if(myIntefaceWeakReference != null &amp;&amp; myIntefaceWeakReference.get() != null){<br>            myIntefaceWeakReference.get().doWorkBeforeBackground();<br>        }<br>    }<br><br>    @Override<br>    protected String doInBackground(Void... voids) {<br>        String result = someNetworkFunction();<br>        return result;<br>    }<br><br>    @Override<br>    protected void onPostExecute(Object s) {<br>        if(myIntefaceWeakReference != null  &amp;&amp; myIntefaceWeakReference.get() != null){<br>           myIntefaceWeakReference.get().doWorkAfterBackground((String)s);<br>        }<br>    }<br>}</pre><pre>interface myInteface {<br>    void doWorkBeforeBackground();<br>    void doWorkAfterBackground(Object result);<br>}</pre><p>In order to start, we need to import coroutines through Gradle. Let’s add the dependency inside the apps <em>build.gradle</em> :<br> implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9&#39;</p><p>Let’s start:</p><pre>doWorkBeforeBackground()   // on Ui thread<br>CoroutineScope(Dispatchers.IO).launch {<br>    try {<br>        val api = someNetworkFunction()<br>        withContext(Dispatchers.Main) <strong>{<br>            </strong>try {<br>                doWorkAfterBackground(api.data);<br>            } catch (e: Exception) {<br>                e.printStackTrace()<br>            }<br>        <strong>}<br>    </strong>} catch (e: Exception) {<br>        e.printStackTrace()<br>    }<br>}</pre><p>So basically the call for “<em>doWorkBeforeBackground()” </em>is being done on the UI thread and being called in the same manner as “<em>onPreExecute</em>” would of being called.(Of course, this part is not a must process like in AsyncTask that onPreExecute doesn’t need to be overridden)</p><p>Now let’s talk about the interesting part which is the Coroutine. As you can see we use something called “<em>CoroutineScope</em>” (Note that all coroutines must run in a scope). The “<em>launch” </em>is a function that creates a coroutine and dispatches the execution of its function body to the corresponding dispatcher.<br>“<em>Dispatchers.IO</em>” indicates that this coroutine should be executed on a thread reserved for I/O operations (it resembles the thread that handles the “<em>doInBackground</em>” operation).</p><p>As you can see I called the “<em>someNetworkFunction()</em>” on the scope of the “<em>Dispatchers.IO”</em> that is <strong>not</strong> the UI thread, by doing so the UI thread won’t be stuck.</p><p>When the result is gotten we proceed to “<em>withContext(Dispatchers.Main)</em>” which is in a way the equivalent of the “<em>onPostExecute</em>” part of the AsyncTask.</p><p>You can see that for this part the selected dispatcher is the “<em>Main</em>” and not “<em>IO</em>” which means we are returning to the UI thread.</p><p>So as you can see there is a lot less code, less room for error and bugs, as well as really readable.</p><p>Of course that when using the replacement I think this is the most perfect solution for some reasons:</p><p>1) As mentioned it has less code which means fewer bugs to be created.</p><p>2) This solution is Kotlin based and not Java-based.</p><p>3) This solution is a lot understandable and readable.</p><p>Hope this seems like a better understanding of the coroutines process.</p><p>If you want me to release a new article about an RxJava solution write in the comments and I will create one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c094b60473dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/asynctask-is-deprecated-now-what-part-2-c094b60473dc">AsyncTask is deprecated, now what? —  part 2</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AsyncTask is deprecated, now what?]]></title>
            <link>https://medium.com/swlh/asynctask-is-deprecated-now-what-f30c31362761?source=rss-5212cf59fc95------2</link>
            <guid isPermaLink="false">https://medium.com/p/f30c31362761</guid>
            <category><![CDATA[asynctask]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Idan Damri]]></dc:creator>
            <pubDate>Tue, 26 May 2020 09:43:34 GMT</pubDate>
            <atom:updated>2020-10-09T14:35:59.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*pG0cJDAlMfiXFPONvdX3qw.png" /></figure><h3>AsyncTask is deprecated, now what? — Part 1</h3><p>If you are reading this because you just heard that starting from Android 11 AsyncTask is deprecated and you are looking for some kind of solution, you might have reached the right place.<br>This article is for you if you haven&#39;t moved to Kotlin you need some kind of Java solution.</p><p>Before we start I have to say that Kotlin offers the use of the amazing “coroutines” for asynchronous tasks. If you want to try it out you can do it with the following link. If you haven’t started working with Kotlin or at least reading about it I would really suggest starting doing so, since Google announced it as their official language for android development(!!). Not only that, but all of their documentation is also written in Kotlin for the new components (the old components have examples and documentation on Kotlin as well as Java) and if you are still not convinced — it reduces development times in average of about 40% which means less writing code, faster go-to-market time, it’s intuitively easy to read and has a lot of key features that I personally like as a developer. But that’s enough about Kotlin, let’s get down to business.</p><p>Let’s say you had the following class that extends AsyncTask:</p><pre>public class myAsyncTask extends AsyncTask&lt;Void, Void, String&gt; {<br><br>    WeakReference&lt;myInteface&gt; myIntefaceWeakReference;<br><br>    public myAsyncTask(myInteface listener) {<br>        this.myIntefaceWeakReference = new WeakReference&lt;&gt;(listener);<br>    }<br><br>    @Override<br>    protected void onPreExecute() {<br>        if(myIntefaceWeakReference != null &amp;&amp; myIntefaceWeakReference.get() != null){<br>            myIntefaceWeakReference.get().doWorkBeforeBackground();<br>        }<br>    }<br><br>    @Override<br>    protected String doInBackground(Void... voids) {<br>        String result = someNetworkFunction();<br>        return result;<br>    }<br><br>    @Override<br>    protected void onPostExecute(Object s) {<br>        if(myIntefaceWeakReference != null  &amp;&amp; myIntefaceWeakReference.get() != null){<br>           myIntefaceWeakReference.get().doWorkAfterBackground((String)s);<br>        }<br>    }<br>}</pre><pre>interface myInteface {<br>    void doWorkBeforeBackground();<br>    void doWorkAfterBackground(Object result);<br>}</pre><p>Now let&#39;s see the transformation I am offering, I’ll show the code first and explain about it afterward:</p><pre>public interface CustomCallable&lt;R&gt; extends Callable&lt;R&gt;{<br>    void setDataAfterLoading(R result);<br>    void setUiForLoading();<br>}</pre><p>I’ve created a CustomCallable interface that extends Callable, I’m using the &lt;R&gt; for generic purposes. Note that Callable is an interface that is why my interface <strong><em>extends</em></strong> it and not <strong><em>implement</em></strong> it!</p><pre>public class TaskRunner {<br><br>    private final Handler handler = new Handler(Looper.<em>getMainLooper</em>());<br>    private final Executor executor = Executors.<em>newCachedThreadPool</em>();<br><br>    public &lt;R&gt; void executeAsync(CustomCallable&lt;R&gt; callable) {<br>        try {<br>            callable.setUiForLoading();<br>            executor.execute(new RunnableTask&lt;R&gt;(handler, callable));<br>        } catch (Exception e) {<br>            Utils.<em>printStackTrace</em>(e);<br>        }<br>    }<br><br>    public static class RunnableTask&lt;R&gt; implements Runnable{<br>        private final Handler handler;<br>        private final CustomCallable&lt;R&gt; callable;<br><br>        public RunnableTask(Handler handler, CustomCallable&lt;R&gt; callable) {<br>            this.handler = handler;<br>            this.callable = callable;<br>        }<br><br>        @Override<br>        public void run() {<br>            try {<br>                final R result = callable.call();<br>                handler.post(new RunnableTaskForHandler(callable, result));<br>            } catch (Exception e) {<br>                Utils.<em>printStackTrace</em>(e);<br>            }<br>        }<br>    }<br><br>    public static class RunnableTaskForHandler&lt;R&gt; implements Runnable{<br><br>        private CustomCallable&lt;R&gt; callable;<br>        private R result;<br><br>        public RunnableTaskForHandler(CustomCallable&lt;R&gt; callable, R result) {<br>            this.callable = callable;<br>            this.result = result;<br>        }<br><br>        @Override<br>        public void run() {<br>            callable.setDataAfterLoading(result);<br>        }<br>    }<br>}</pre><p>You can see that I added a class named TaskRunner, this will act as a handler-wrapper class. This class has a handler and an executor (Not like the <a href="https://bulbapedia.bulbagarden.net/wiki/Exeggutor_(Pok%C3%A9mon)">pokemon</a>) to handle thread work with the ThreadPool. The <em>executeAsync </em>is the function that calls the setUiForLoading<em>() </em>function that you don’t have to implement in case you have nothing to do. Afterward, the executor creates the RunnableTask(equivalent to AsyncTasks <em>doInBackground</em>). This runnable is a generic Runnable thanks to &lt;R&gt; tag.</p><p>The <em>RunnableTask.run() </em>function handles the <em>call() </em>function and returns its results so we can post it on to the handler to return to the UI thread and finally use the <em>setDataAfterLoading(result)</em> (equivalent to onPostExecute).</p><p>The basic idea behind this is to create a generic run with 3 main functions:</p><ul><li>setUiForLoading<em>()</em> on main UI thread.</li><li>setDataAfterLoading<em>(R result)</em> on the main UI thread.</li><li><em>call()</em> function that returns a generic result as an object that runs on a different thread.</li></ul><p>If you’ve gotten this far — it’s not a long way to go.</p><p>In order to keep it as a simple implementation, I created this abstract base class:</p><pre>public abstract class BaseTask&lt;R&gt; implements CustomCallable&lt;R&gt; {<br>    @Override<br>    public void setUiForLoading() {<br><br>    }<br><br>    @Override<br>    public void setDataAfterLoading(R result) {<br><br>    }<br><br>    @Override<br>    public R call() throws Exception {<br>        return null;<br>    }<br>}</pre><p>Let’s create a class that extends the BaseTask&lt;R&gt; class:</p><pre>public class NetworkTask extends BaseTask {<br><br>    private final iOnDataFetched listener;//listener in fragment that shows and hides ProgressBar</pre><pre>public NetworkTask(iOnDataFetched onDataFetchedListener,) {<br>        this.listener = onDataFetchedListener;<br>    }<br><br>    @Override<br>    public Object call() throws Exception {<br>     <br>       Object result = null;<br>      result = someNetworkFunction();//some network request for example<br>       return result;</pre><pre>    }<br><br>    @Override<br>    public void setUiForLoading() {</pre><pre>        listener.showProgressBar();</pre><pre>    }<br><br>    @Override<br>    public void setDataAfterLoading(Object result) {</pre><pre>        listener.setDataInPageWithResult(result);</pre><pre>        listener.hideProgressBar();</pre><pre>    }<br>}</pre><pre>public interface iOnDataFetched{</pre><pre>    void showProgressBar();<br>    void hideProgressBar();<br>    void setDataInPageWithResult(Object result);</pre><pre>}</pre><p>Now in order for it to run we replace the following code in the fragment:</p><pre>new myAsyncTask(this).execute();</pre><p>With:</p><pre>TaskRunner runner = new TaskRunner();<br><br>runner.executeAsync(new NetworkTask(this));</pre><p>And ‘voua la’ the magic works. For each Async task that you want to replace all you had to do is create a function that extends the BaseTask, copy the code from your previous AsyncTask, and replace the call of the old AsyncTask, to the new TaskRunner and execute the new class.</p><p>By using this implementation you have to construct once the <em>TaskRunner</em>, <em>BaseTask </em>object, <em>myInteface</em>. After that you just need to create a new class that extends BaseTask and you’re done. The process is really easy to understand, debug, read and really low amount of code to re-write for each task you wish to create.</p><p>I had to come up with this solution for my workplace since we haven&#39;t moved to Kotlin yet. Like I said in the second paragraph, it’s better if you use Kotlins <strong><em>coroutines</em></strong>, but if you had no choice like me and you want to save yourself some writing for the future — enjoy these pieces of code. <br>Here is another article that converts the <a href="https://medium.com/@idandamri/asynctask-is-deprecated-now-what-part-2-c094b60473dc">AsyncTask to Kotlins coroutines</a>.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f30c31362761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/asynctask-is-deprecated-now-what-f30c31362761">AsyncTask is deprecated, now what?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>