<?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"><channel><title><![CDATA[Sajal's blog]]></title><description><![CDATA[Android platform engineer specializing in app and framework development, performance optimization. I have versatile experience across different Android form fac]]></description><link>https://blog.sajalrg.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 11 Apr 2026 14:52:40 GMT</lastBuildDate><atom:link href="https://blog.sajalrg.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Android BootUp Sequence: Major Milestones]]></title><description><![CDATA[1. Power On
When the user presses the power button, it loads the bootloader from a predefined location in ROM to RAM and executes it.
2. Bootloader
This is a small program that loads before kernel. It primarily loads the kernel and executes it.
3. Li...]]></description><link>https://blog.sajalrg.com/android-bootup-sequence-major-milestones</link><guid isPermaLink="true">https://blog.sajalrg.com/android-bootup-sequence-major-milestones</guid><category><![CDATA[aosp]]></category><category><![CDATA[framework]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android app development]]></category><category><![CDATA[#androidframeworks ]]></category><category><![CDATA[Android framework]]></category><category><![CDATA[#AndroidCore]]></category><category><![CDATA[android component]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Tue, 23 Jul 2024 16:25:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1721795469282/e2613e5b-2351-420f-9d19-d61492867ee0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-1-power-on">1. Power On</h3>
<p>When the user presses the power button, it loads the bootloader from a predefined location in ROM to RAM and executes it.</p>
<h3 id="heading-2-bootloader">2. Bootloader</h3>
<p>This is a small program that loads before kernel. It primarily loads the kernel and executes it.</p>
<h3 id="heading-3-linux-kernel">3. Linux Kernel</h3>
<p>When the kernel starts, it performs the initial setup, including memory management, drivers (including the binder driver), cache, scheduling, etc. Once the kernel is loaded and the setup is complete, it starts the <code>init</code> process.</p>
<h3 id="heading-4-init-process">4. Init Process</h3>
<p>This is the first user-space process started by Android.</p>
<ul>
<li>It creates and mounts file directories required for startup, such as <code>/dev</code> and <code>/proc</code>.</li>
<li>It initializes system properties.</li>
<li>It starts native services like <code>ServiceManager</code> and <code>zygote</code>.</li>
</ul>
<p>This process parses and executes the <code>init.rc</code> script. The implementation of <code>init</code> can be found at <code>system/core/init</code> and the <code>init.rc</code> script can be found at <code>system/core/rootdir/</code>.</p>
<h3 id="heading-5-zygote">5. Zygote</h3>
<p>This is the base/template process that gets forked every time a new application is launched.</p>
<ul>
<li>It preloads common libraries, resources (eg. Java classes, Android framework classes). Hence, when an application needs to be launched, it will not be starting from scratch.</li>
<li>It loads the VM (Virtual Machine), where the application's java bytecode will be executed.</li>
<li>Zygote starts the system server process.</li>
</ul>
<p>At this time, the boot animation will be visible.</p>
<p>Note: After initialization, Zygote will just wait for AMS (Activity Manager Service) to request start of a new process. When it receives such request, it will fork itself and create to new process.</p>
<h3 id="heading-6-system-server">6. System Server</h3>
<p>The system server starts all the SystemServices (e.g. PMS, AMS etc.). It also creates and starts the binder thread pool. This is implemented in <code>frameworks/base/services/java/com/android/server/SystemServer.java</code></p>
<h3 id="heading-7-launcher-systemui">7. Launcher, SystemUI</h3>
<p>SystemUI and Launcher are core application in android launcher during boot time.
SystemUI is responsible for various core UI components like notifications, the lock screen, the status bar, and the navigation bar.
The Launcher is the activity that is base of all the activities, the user can view and launch other applications from the launcher.</p>
<p>The above flow can be summarized in the following diagram:
<img src="https://www.plantuml.com/plantuml/png/LPBBRjmw38RtUWe-G2xxipX8qg95qGmoY94k6dH1oup3HXPTYauoVVfAjXNFR2nUg8_KRrubGxLf2CxO0i5rx5IuWniHUnYXeJyJHK_EfHUE8oeEu6KO9LAqnWxvXf8tZ7t8DHyPsCiRwLs4HxTQxbQmIz1cRCWMAJof371_jmCJkB_UkLz7rs-siaUtEIi4OmVqJduoIc3F12-aaS89uViSohTlEKxlg-lsf4-YGmAER8m14jaqpi1PXmLNaZ2gU4hf15eI6LaEzuKr6Ko9D8tegTRdcggX-wI4PSIEYqQYJEciTkQ_EP4EoMWeLqTIA-awHaJZLu9CV-MCTMluvw4Ne-EPrb2UQZMsEVpKeaaLxSVk3FPAONO2juhAj6Yfb6HIlxLV1olTIS_W3Jd7id1mlMjEcZTpNJFNvH4M5nRVDGjhg-6vXLzLQJbsf5dmx7SmYeGJz2rEqJyNBApSXszkXn5xIX35-8az6alCo23-1L86KvoVO5F6exhAS7kLL-xMRMan4Q3F0hCTvcU9bKOuZc5b0aSZHL_iF5LTOZZlv2sU_mz7AxcPDLkNRJa-elFMb4-DrB-v73LwegdRd2F-nxESfp9dVeEKupDZhpX0Uu06VsEu_mhFPcFwx_Ao3T9Vf1BK_YABVEdS5SLk6i8_" alt="Android Bootup Sequence Flow" /></p>
<p>In subsequent posts, we will dive deeper into the milestones shown above.</p>
]]></content:encoded></item><item><title><![CDATA[Internals of HandlerThread in Android]]></title><description><![CDATA[In previous parts, we've delved into Handler, Looper and Message, understanding their roles in enabling code execution within a specified thread and facilitating safe communication between threads.
The HandlerThread class combines these concepts, sim...]]></description><link>https://blog.sajalrg.com/internals-of-handlerthread-in-android</link><guid isPermaLink="true">https://blog.sajalrg.com/internals-of-handlerthread-in-android</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android development]]></category><category><![CDATA[handler-android]]></category><category><![CDATA[looper-android]]></category><category><![CDATA[Threads]]></category><category><![CDATA[thread]]></category><category><![CDATA[message queue]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[aosp]]></category><category><![CDATA[#androidframeworks ]]></category><category><![CDATA[HandlerThread]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Thu, 22 Feb 2024 16:03:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708616222051/d252dbbe-ab04-435c-b63d-9636f8b68d4c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In previous parts, we've delved into <code>Handler</code>, <code>Looper</code> and <code>Message</code>, understanding their roles in enabling code execution within a specified thread and facilitating safe communication between threads.</p>
<p>The <code>HandlerThread</code> class combines these concepts, simplifying the acquisition of <code>Looper</code> and <code>Handler</code> objects. In this article, we'll explore the implementation of <code>HandlerThread</code> referencing some AOSP code examples.</p>
<h2 id="heading-internals-of-handlerthread">Internals of HandlerThread</h2>
<p><a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/os/HandlerThread.java;drc=be9f42d83645781b78f9448475156ad44bec23a8"><code>HandlerThread</code></a> extends the <code>Thread</code> class, providing additional functionality for initializing a Looper and Handler for the associated thread.</p>
<p>Here's the class definition:</p>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * A {<span class="hljs-doctag">@link</span> Thread} that has a {<span class="hljs-doctag">@link</span> Looper}.
 * The {<span class="hljs-doctag">@link</span> Looper} can then be used to create {<span class="hljs-doctag">@link</span> Handler}s.
 * &lt;p&gt;
 * Note that just like with a regular {<span class="hljs-doctag">@link</span> Thread}, {<span class="hljs-doctag">@link</span> #start()} must still be called.
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HandlerThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{
    <span class="hljs-comment">// SajalRG: Implementation details...</span>
}
</code></pre>
<p>UML class diagram of <code>HandlerThread</code> is shown below:
<img src="//www.plantuml.com/plantuml/svg/NP1D2i8m48NtEKN0ZIAzG71HN2cuADWBH3Dg83zrcWX5lRiCaq3hAfFlJTxBJ3icZIbx9wvEZwFi7mZQoBUGSeivh3TAlg8ruYjAmq47um1dVVuKum2e99z4UckKj25HtQ6DQDDKGUEBXQfUVrbqlKDYDu9S5Sp1_9BKkSapsqJe4gC37IewwnkuYOGz2mkheo65_xQAWSCwX44Za5J7BnFlFaspN88GBGIJlVi1" alt="class diagram handler" /></p>
<p>As demonstrated, <code>HandlerThread</code> essentially functions as a regular Java thread with added capabilities for constructing Looper and providing access to the Looper and Handler instances.</p>
<h2 id="heading-recap-construction-of-looper">Recap: Construction of Looper</h2>
<p>Examining the <code>run()</code> method of <code>HandlerThread</code>, we observe the process of Looper initialization, as discussed in first article of this series.</p>
<p><code>Looper.prepare()</code> will create a new instance and can be called only once inside a Thread. <code>Looper.loop()</code> waits for message to appear in MessageQueue and process them. For detailed information and innerworking of this, I suggest to read <a target="_blank" href="https://blog.sajalrg.com/looper-handler-in-android-part-1-looper">this</a> article.</p>
<pre><code class="lang-java">    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        mTid = Process.myTid();
        Looper.prepare();
        <span class="hljs-keyword">synchronized</span> (<span class="hljs-keyword">this</span>) {
            mLooper = Looper.myLooper();
            notifyAll();
        }
        Process.setThreadPriority(mPriority);
        onLooperPrepared();
        Looper.loop();
        mTid = -<span class="hljs-number">1</span>;
    }
</code></pre>
<h2 id="heading-uses-of-handlerthread">Uses of HandlerThread</h2>
<p>Now that we understand what <code>HandlerThread</code> is and how it operates, let's explore its practical utility.</p>
<h4 id="heading-example1-settings-app-wifidialogactivityjava">Example1: Setting's App - WifiDialogActivity.java</h4>
<p>In this example, <code>HandlerThread</code> is used to obtain a <code>Handler</code> object for the underlying Thread.
<a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:packages/apps/Settings/src/com/android/settings/wifi/WifiDialogActivity.java;l=133;drc=be23c28ff299dc1143f714dc3fa27507d44fbe72">View Full Code Here</a>.</p>
<pre><code class="lang-java">        <span class="hljs-keyword">if</span> (mIsWifiTrackerLib) {
            <span class="hljs-comment">// SajalRG: construct new HandlerThread</span>
            mWorkerThread = <span class="hljs-keyword">new</span> HandlerThread(
                    TAG + <span class="hljs-string">"{"</span> + Integer.toHexString(System.identityHashCode(<span class="hljs-keyword">this</span>)) + <span class="hljs-string">"}"</span>,
                    Process.THREAD_PRIORITY_BACKGROUND);
            mWorkerThread.start(); <span class="hljs-comment">/* SajalRG: actually starts the thread */</span>
            <span class="hljs-comment">// SajalRG: other code removed for simplicity</span>
            mNetworkDetailsTracker = FeatureFactory.getFactory(<span class="hljs-keyword">this</span>)
                    .getWifiTrackerLibProvider()
                    .createNetworkDetailsTracker(
                            getLifecycle(),
                            <span class="hljs-keyword">this</span>,
                            <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper()), <span class="hljs-comment">/* SajalRG: passing handler for main looper */</span>
                            mWorkerThread.getThreadHandler(), <span class="hljs-comment">/* SajalRG: passing handler for the new thread */</span>
                            elapsedRealtimeClock,
                            MAX_SCAN_AGE_MILLIS,
                            SCAN_INTERVAL_MILLIS,
                            mIntent.getStringExtra(KEY_CHOSEN_WIFIENTRY_KEY));
        }
</code></pre>
<h4 id="heading-example-2-camera2-app-capturemodulejava">Example 2: Camera2 App - CaptureModule.java</h4>
<p>Here, HandlerThread is utilized to acquire a Looper for creating a new Handler object.<a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:packages/apps/Camera2/src/com/android/camera/CaptureModule.java;l=411;drc=00dea6cdc9fa0de0914b9f18c9e05fd414728215">View Full Code Here</a>.</p>
<pre><code class="lang-java">    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">(CameraActivity activity, <span class="hljs-keyword">boolean</span> isSecureCamera, <span class="hljs-keyword">boolean</span> isCaptureIntent)</span> </span>{
        <span class="hljs-comment">// SajalRG: other code removed for simplicity</span>
        HandlerThread thread = <span class="hljs-keyword">new</span> HandlerThread(<span class="hljs-string">"CaptureModule.mCameraHandler"</span>);
        thread.start(); <span class="hljs-comment">/* Thread started */</span>
        <span class="hljs-comment">/* Create new Handler using looper from handler thread */</span>
        mCameraHandler = <span class="hljs-keyword">new</span> Handler(thread.getLooper());
        <span class="hljs-comment">// SajalRG: other code removed for simplicity</span>
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p> <code>HandlerThread</code> simplifies the creation of a Looper, which otherwise would require manually extending <code>Thread</code> class and overloading the <code>run()</code> method with similar implementation. Understanding the functionality of <code>HandlerThread</code> equips us to leverage its benefits in our projects effectively.</p>
<p>In the next article, we'll address potential memory leak issues with Handler and how to mitigate them.</p>
<p>If you find these articles helpful, please consider liking or commenting to support future content. If you have any questions or topics you'd like covered, feel free to leave a comment below.</p>
]]></content:encoded></item><item><title><![CDATA[Looper, Handler in Android Part 4 - Handler]]></title><description><![CDATA[This is the final article in our series on Introduction Looper and Handler in Android. To fully grasp the concepts discussed here, it's assumed that you have read or are familiar with the content covered in previous parts. If not, I recommend revisit...]]></description><link>https://blog.sajalrg.com/looper-handler-in-android-part-4-handler</link><guid isPermaLink="true">https://blog.sajalrg.com/looper-handler-in-android-part-4-handler</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android development]]></category><category><![CDATA[aosp]]></category><category><![CDATA[handler]]></category><category><![CDATA[handler-android]]></category><category><![CDATA[looper-android]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[Threads]]></category><category><![CDATA[asynchronous]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Wed, 14 Feb 2024 04:55:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Nsaqv7v2V7Q/upload/e68f3e3c857b22b60b8f2ba094b45efd.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is the final article in our series on Introduction Looper and Handler in Android. To fully grasp the concepts discussed here, it's assumed that you have read or are familiar with the content covered in previous parts. If not, I recommend revisiting those articles first.</p>
<h2 id="heading-recap-of-how-to-use-handler">Recap of How to Use Handler</h2>
<p>Handler can be utilized in two main ways:</p>
<ol>
<li><p><strong>Passing Runnable</strong>: Adding or posting operation to be executed directly inside the thread from another thread. This is accomplished using the <code>post()</code> method of <code>Handler</code>.</p>
</li>
<li><p><strong>Sending Message</strong>: Sending a message about an operation that needs to be done inside the thread from another thread. This involves a combination of the <code>sendMessage()</code> and <code>handleMessage()</code> methods of <code>Handler</code>.    </p>
<p>While we coverted the <code>post()</code> method extensively in part3, here we will delve into the <code>sendMessage()</code> and <code>handleMessage()</code> methods of the <code>Handler</code>.</p>
</li>
</ol>
<h2 id="heading-when-to-use-sendmessage">When to use <code>sendMessage()</code></h2>
<p>As the name suggests, <code>sendMessage()</code> is used to send a <code>Message</code> object to a <code>Handler</code> and <code>handleMessage()</code> will perform certain operation on the received <code>Message</code>. The two methods, <code>sendMessage()</code> and <code>handleMessage()</code>, must always be used in conjunction. If you use<code>sendMessage()</code> to send a <code>Message</code> to a <code>Handler</code>, the <code>Handler</code> must also implement its <code>handleMessage()</code> to process that message.</p>
<p>Unlike <code>post()</code>, which is suitable for executing a block of code, <code>sendMessage()</code> is used for reusable pieces of code that need to be handled frequently within your thread. For example, when multiple parts of your code needs to save documents, you can use <code>sendMessage()</code> to organize your code more efficiently. All the logic related to file operations will be handled separately, enabling reuse, concurrency, separation of concerns, and synchronous access to the file I/O operations. By passing the path as an argument, the same code can be utilized for multiple other documents, further enhancing its flexibility and maintainability.</p>
<blockquote>
<p>Note: In terms of synchronicity, The <code>sendMessage()</code> call itself is asynchronous, non-blocking and can be executed from any thread. The <code>handleMessage()</code> method associated with it will always be invoked synchronously and will run on the same thread that the Handler operates on.</p>
</blockquote>
<h2 id="heading-internals-of-sendmessage">Internals of <code>sendMessage()</code></h2>
<p>Internally both <code>post()</code> and <code>sendMessage()</code> work similarly. The difference lies in how they are handled as seen above. Typically, <code>post()</code> is used for running a one-off block of code in another thread (e.g., updating the UI), and <code>sendMessage()</code> is used for operations that need to be repeated. However, there is no strict rule in the language construct, and it largely depends on your use case and programming style.</p>
<p>To reiterate, here's an excerpt from the Android documentation of <a target="_blank" href="https://developer.android.com/reference/android/os/Handler"><code>Handler</code></a></p>
<blockquote>
<p>The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler).</p>
</blockquote>
<p>Similar to <code>post()</code>, <code>sendMessage()</code> also calls <code>sendMessageDelayed()</code> function to add the <code>Message</code> to the <code>MessageQueue</code> (refer to part 3 for the detailed flow of <code>post()</code>). The only difference lies in the <code>dispatchMessage</code> method which calls <code>handleMessage()</code> instead.</p>
<pre><code class="lang-java">    <span class="hljs-comment">// SajalRG: adds message to the queue, called from any thread</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg)</span> </span>{
        <span class="hljs-keyword">return</span> sendMessageDelayed(msg, <span class="hljs-number">0</span>);
    }

    <span class="hljs-comment">/**
     * Handle system messages here.
     */</span>
   <span class="hljs-comment">// SajalRG: executed from Looper.loop() inside the thread represented by handler</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg)</span> </span>{
        <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
            handleCallback(msg);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">if</span> (mCallback != <span class="hljs-keyword">null</span>) {
                <span class="hljs-keyword">if</span> (mCallback.handleMessage(msg)) {
                    <span class="hljs-keyword">return</span>;
                }
            }
            handleMessage(msg);
        }
    }
</code></pre>
<h2 id="heading-example-from-aosp-systemui">Example from AOSP SystemUI</h2>
<p>Let's examine an example from AOSP on how this pair can be utilized. We will take a look at the <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java"><code>CommandQueue</code></a> class.</p>
<blockquote>
<p>Note: Our objective here is not to delve into the intricacies of the <code>CommandQueue</code> class itself. Instead, we aim to focus solely on how it leverages the <code>sendMessage()</code> and <code>handleMessage()</code> methods. This approach provides insight into real-world usage in larger projects, offering a practical understanding rather than relying on contrived examples.</p>
</blockquote>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * This class takes the functions from IStatusBar that come in on
 * binder pool threads and posts messages to get them onto the main
 * thread, and ...
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommandQueue</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">IStatusBar</span>.<span class="hljs-title">Stub</span> <span class="hljs-keyword">implements</span>
        <span class="hljs-title">CallbackController</span>&lt;<span class="hljs-title">Callbacks</span>&gt; </span>{
</code></pre>
<p>In this example, <code>CommandQueue</code> also <code>extends</code> the <code>IStatusBar.stub()</code>, which we can ignore for now but it could be a topic for furture articles on <code>Binder</code> and <code>AIDL</code>. <code>CallbackController</code> is an <code>interface</code> which the <code>CommandQueue</code> implements, but we won't explore it further in this post.</p>
<p>For our purpose, <code>CommandQueue</code> has some methods that are called from other threads, referred to as <code>binder pool threads</code>, and it will post the messages onto the main thread.</p>
<h3 id="heading-understanding-commandqueue">Understanding CommandQueue</h3>
<p>If you view the <code>CommandQueue</code> class from <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java">this link</a>, you might notice that there is no <code>sendMessage()</code> call in the class, even though we are using this as an example for <code>sendMessage()</code>.</p>
<p>To understand this, let's look at <code>Message</code> class. We partially covered the <code>Message</code> class in part 2, please review if you haven't already. Now, let's introduce method <code>sendToTarget</code> class which is used here. It internally calls the <code>sendMessage()</code> for us. Both approaches are okay.</p>
<pre><code class="lang-java">    <span class="hljs-comment">/**
     * Sends this Message to the Handler specified by {<span class="hljs-doctag">@link</span> #getTarget}.
     * Throws a null pointer exception if this field has not been set.
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendToTarget</span><span class="hljs-params">()</span> </span>{
        target.sendMessage(<span class="hljs-keyword">this</span>);
    }
</code></pre>
<p>Also, instead of using <code>Message.obtain()</code> to create new <code>Message</code>, as we saw in part3, <code>Handler.obtainMessage()</code> is used here, which internally does the same. Below is the excerpt from the <code>Handler</code> class listing all other possible ways to obtain <code>Message</code>.</p>
<pre><code class="lang-java">    <span class="hljs-meta">@NonNull</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> Message <span class="hljs-title">obtainMessage</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Message.obtain(<span class="hljs-keyword">this</span>);
    }

    <span class="hljs-comment">/**
     * Same as {<span class="hljs-doctag">@link</span> #obtainMessage()}, except that it also sets the what member of the returned Message.
     * 
     * <span class="hljs-doctag">@param</span> what Value to assign to the returned Message.what field.
     * <span class="hljs-doctag">@return</span> A Message from the global message pool.
     */</span>
    <span class="hljs-meta">@NonNull</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> Message <span class="hljs-title">obtainMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> what)</span> </span>{
        <span class="hljs-keyword">return</span> Message.obtain(<span class="hljs-keyword">this</span>, what);
    }

    <span class="hljs-comment">/**
     * 
     * Same as {<span class="hljs-doctag">@link</span> #obtainMessage()}, except that it also sets the what and obj members 
     * of the returned Message.
     * 
     * <span class="hljs-doctag">@param</span> what Value to assign to the returned Message.what field.
     * <span class="hljs-doctag">@param</span> obj Value to assign to the returned Message.obj field.
     * <span class="hljs-doctag">@return</span> A Message from the global message pool.
     */</span>
    <span class="hljs-meta">@NonNull</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> Message <span class="hljs-title">obtainMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> what, <span class="hljs-meta">@Nullable</span> Object obj)</span> </span>{
        <span class="hljs-keyword">return</span> Message.obtain(<span class="hljs-keyword">this</span>, what, obj);
    }

    <span class="hljs-comment">/**
     * 
     * Same as {<span class="hljs-doctag">@link</span> #obtainMessage()}, except that it also sets the what, arg1 and arg2 members of the returned
     * Message.
     * <span class="hljs-doctag">@param</span> what Value to assign to the returned Message.what field.
     * <span class="hljs-doctag">@param</span> arg1 Value to assign to the returned Message.arg1 field.
     * <span class="hljs-doctag">@param</span> arg2 Value to assign to the returned Message.arg2 field.
     * <span class="hljs-doctag">@return</span> A Message from the global message pool.
     */</span>
    <span class="hljs-meta">@NonNull</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> Message <span class="hljs-title">obtainMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> what, <span class="hljs-keyword">int</span> arg1, <span class="hljs-keyword">int</span> arg2)</span> </span>{
        <span class="hljs-keyword">return</span> Message.obtain(<span class="hljs-keyword">this</span>, what, arg1, arg2);
    }

    <span class="hljs-comment">/**
     * 
     * Same as {<span class="hljs-doctag">@link</span> #obtainMessage()}, except that it also sets the what, obj, arg1,and arg2 values on the 
     * returned Message.
     * <span class="hljs-doctag">@param</span> what Value to assign to the returned Message.what field.
     * <span class="hljs-doctag">@param</span> arg1 Value to assign to the returned Message.arg1 field.
     * <span class="hljs-doctag">@param</span> arg2 Value to assign to the returned Message.arg2 field.
     * <span class="hljs-doctag">@param</span> obj Value to assign to the returned Message.obj field.
     * <span class="hljs-doctag">@return</span> A Message from the global message pool.
     */</span>
    <span class="hljs-meta">@NonNull</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> Message <span class="hljs-title">obtainMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> what, <span class="hljs-keyword">int</span> arg1, <span class="hljs-keyword">int</span> arg2, <span class="hljs-meta">@Nullable</span> Object obj)</span> </span>{
        <span class="hljs-keyword">return</span> Message.obtain(<span class="hljs-keyword">this</span>, what, arg1, arg2, obj);
    }
</code></pre>
<p>In above code snippet, different signature which allows us to pass additional information to the <code>Message</code> are also listed. Here, <code>what</code> is primarily used in <code>handleMessage()</code> identify which operation to perform.</p>
<h3 id="heading-message-flow-in-commandqueue">Message flow in CommandQueue</h3>
<p>Let's explore the <code>addQsTile</code> method to explore the message flow. First, the method is called from the binder thread.</p>
<pre><code class="lang-java">    <span class="hljs-comment">// SajalRG: create new handler using the main looper</span>
    <span class="hljs-keyword">private</span> Handler mHandler = <span class="hljs-keyword">new</span> H(Looper.getMainLooper());
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addQsTile</span><span class="hljs-params">(ComponentName tile)</span> </span>{
        <span class="hljs-keyword">synchronized</span> (mLock) {
            <span class="hljs-comment">// SajalRG: get message object and send the message</span>
            mHandler.obtainMessage(MSG_ADD_QS_TILE, tile).sendToTarget();
        }
    }
</code></pre>
<p>Then, it is handled inside the Handler</p>
<pre><code class="lang-java">    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">H</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Handler</span> </span>{
        <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">H</span><span class="hljs-params">(Looper l)</span> </span>{
            <span class="hljs-keyword">super</span>(l);
        }
        <span class="hljs-comment">// SajalRG: handleMessage is called in conjunction to the sendMessage</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span><span class="hljs-params">(Message msg)</span> </span>{
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> what = msg.what &amp; MSG_MASK;
            <span class="hljs-comment">// SajalRG: what is used to identify which operation to execute</span>
            <span class="hljs-keyword">switch</span> (what) {
                <span class="hljs-comment">// SajalRG: other cases</span>
                <span class="hljs-keyword">case</span> MSG_ADD_QS_TILE:
                    <span class="hljs-comment">// SajalRG: actual operation happening inside the main thread</span>
                    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; mCallbacks.size(); i++) {
                        mCallbacks.get(i).addQsTile((ComponentName) msg.obj);
                    }
                    <span class="hljs-keyword">break</span>;
                <span class="hljs-comment">// SajalRG: other cases</span>
            }
        }
    }
</code></pre>
<h2 id="heading-whats-next">What's next</h2>
<p>This post concludes our introduction to <code>Handler</code>, <code>Looper</code> and <code>Thread</code>. I hope you have a clearer understanding of the subject and how they are interconnected at a high level. I'd still like to continue this series addressing some misconceptions I'd come across and answer some frequently asked questions related to this topic. If you have any specific topics or query you'd like me to cover, please feel free to leave a comment.</p>
<p>Your support serves as great encouragement for me to continue creating and sharing content.</p>
]]></content:encoded></item><item><title><![CDATA[Looper, Handler in Android Part 3 - Handler]]></title><description><![CDATA[This article is the third in a series on Looper and Handler in Android. To fully understand the concepts discussed here, it's assumed that you have read or are already familiar with the concepts covered in part1 and part2. If not, I recommend visitin...]]></description><link>https://blog.sajalrg.com/looper-handler-in-android-part-3-handler</link><guid isPermaLink="true">https://blog.sajalrg.com/looper-handler-in-android-part-3-handler</guid><category><![CDATA[Android]]></category><category><![CDATA[aosp]]></category><category><![CDATA[Threads]]></category><category><![CDATA[java-thread]]></category><category><![CDATA[handler]]></category><category><![CDATA[handler-android]]></category><category><![CDATA[looper-android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android development]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[Threading]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Tue, 30 Jan 2024 04:48:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1706591672078/cc16babf-cd39-4b28-a60a-828c739cdd8c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is the third in a series on Looper and Handler in Android. To fully understand the concepts discussed here, it's assumed that you have read or are already familiar with the concepts covered in <a target="_blank" href="https://blog.sajalrg.com/looper-handler-in-android-part-1-looper">part1</a> and <a target="_blank" href="https://blog.sajalrg.com/looper-handler-in-android-part-2-handler">part2</a>. If not, I recommend visiting those articles first.</p>
<p>In this article, we will explore deeper into the <code>post()</code> method of <code>Handler</code>, with  an example. By the end of this article, you would have a clear understanding of how the <code>post()</code> method executes your code in a different thread.</p>
<h2 id="heading-how-to-use-handler">How to use Handler</h2>
<p>There are two main way <code>Handler</code> can be used in programming:</p>
<ol>
<li>Adding or posting operation to be executed directly inside the thread from another thread. This flow is invoked by the <code>post()</code> method of <code>Handler</code>.</li>
<li>Sending a message about the operation which needs to be done inside the thread from another thread. This flow is invoked by a combination of the<code>sendMessage()</code> and <code>handleMessage()</code> methods of <code>Handler</code>.</li>
</ol>
<h2 id="heading-when-to-use-post">When to use <code>post()</code></h2>
<p>The <code>post()</code> method is particularly useful when you want to quickly run a block of code in another thread. For example, if you are running some computationally intensive operation in a background thread but want to post updates to the UI, then you can use a <code>Handler</code> attached to the <code>MainThread</code> for same.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Example code demonstrating the usage of post() method</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadWithLongRunningOperation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Some long running operation</span>

        <span class="hljs-comment">// Post intermediate progress to UI</span>
        Handler mainThreadHandler = <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper());
        mainThreadHandler.post(<span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
                <span class="hljs-comment">// update UI</span>
            }
        });

        <span class="hljs-comment">// Continue operation</span>

        <span class="hljs-comment">// Update UI to show completion (here, runnable is posted using lambda)</span>
        mainThreadHandler.post(() -&gt; {
            <span class="hljs-comment">// Update UI</span>
        });
    }
}
</code></pre>
<h2 id="heading-inner-working-of-post">Inner working of <code>post()</code></h2>
<p>The signature of the post method is</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">post</span> <span class="hljs-params">(Runnable r)</span></span>
</code></pre>
<p>From part 2, we know that <code>Handler</code> is used to interact with the <code>Message</code> loop, and <code>Looper</code> only operates on the <code>Message</code> object. So, <code>post()</code> will first convert the <code>Runnable</code> to a <code>Message</code> and add it to the queue as shown below AOSP code snippet of <code>Handler.java</code>:</p>
<pre><code class="lang-java">    <span class="hljs-comment">// Method to convert Runnable to Message</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Message <span class="hljs-title">getPostMessage</span><span class="hljs-params">(Runnable r)</span> </span>{
        Message m = Message.obtain();
        m.callback = r;
        <span class="hljs-keyword">return</span> m;
    }

    <span class="hljs-comment">/**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached.
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">post</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Runnable r)</span> </span>{
       <span class="hljs-keyword">return</span>  sendMessageDelayed(getPostMessage(r), <span class="hljs-number">0</span>);
    }

    <span class="hljs-comment">/**
     * Enqueue a message into the message queue after all pending messages
     * before (current time + delayMillis). You will receive it in
     * {<span class="hljs-doctag">@link</span> #handleMessage}, in the thread attached to this handler.
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageDelayed</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg, <span class="hljs-keyword">long</span> delayMillis)</span> </span>{
        <span class="hljs-keyword">if</span> (delayMillis &lt; <span class="hljs-number">0</span>) {
            delayMillis = <span class="hljs-number">0</span>;
        }
        <span class="hljs-keyword">return</span> sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

    <span class="hljs-comment">/**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) &lt;var&gt;uptimeMillis&lt;/var&gt;.
     * &lt;b&gt;The time-base is {<span class="hljs-doctag">@link</span> android.os.SystemClock#uptimeMillis}.&lt;/b&gt;
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {<span class="hljs-doctag">@link</span> #handleMessage}, in the thread attached
     * to this handler.
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">sendMessageAtTime</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg, <span class="hljs-keyword">long</span> uptimeMillis)</span> </span>{
        MessageQueue queue = mQueue;
        <span class="hljs-keyword">if</span> (queue == <span class="hljs-keyword">null</span>) {
            RuntimeException e = <span class="hljs-keyword">new</span> RuntimeException(
                    <span class="hljs-keyword">this</span> + <span class="hljs-string">" sendMessageAtTime() called with no mQueue"</span>);
            Log.w(<span class="hljs-string">"Looper"</span>, e.getMessage(), e);
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
        }
        <span class="hljs-keyword">return</span> enqueueMessage(queue, msg, uptimeMillis);
    }
</code></pre>
<blockquote>
<p>Note: You can also use <code>Handler</code> to post block of code to execute on same or another thread with some delay using <code>postDelayed</code> method. If you want to execute the <code>Runnable</code> after some time instead of immediately you can replace <code>post</code> with <code>postDelayed</code>. Using <code>postDelayed</code> will call <code>sendMessageDelayed</code> method with the delay provided in the parameter instead of 0 as shown above.</p>
</blockquote>
<p>Finally, the runnable is executed inside <code>dispatchMessage()</code> from the <code>loop()</code> method we saw in part2.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg)</span> </span>{
    <span class="hljs-keyword">if</span> (msg.callback != <span class="hljs-keyword">null</span>) {
        handleCallback(msg);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// Handle other types of messages</span>
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleCallback</span><span class="hljs-params">(Message message)</span> </span>{
    message.callback.run();
}
</code></pre>
<p>Adding these new pieces to our sequence diagram from part 2, results in below diagram
<img src="https://cdn-0.plantuml.com/plantuml/png/TPB1JWCX48RlynJZhMtIzhwfJOqUDD544tq02fEMoB8h3CQ-lP2bB77N2yCkt_pCpyp1it0SMWDzZ5hgNbZ63qyEm7HT3yzn8OVhFRwGz-94Ru42DMZfXnTB49Brjs32WHk_QneW2IQDHs6L8TVWReVIKGBFmozS30fBtE-BofM7774TDP9MWuuuE8lQHWDMqlI6llEnm99P7vs8N-DfBh66YilckjbqHnRQrbRp2UI8ww9TwdhAPSrUxycgdFj0Hbn8rINCWtVyhblwXoFxbPvvz3DIV_esONDSGasbjA6XnL0nNGQYkbzftmkMvwe0OHZR_89I67CKyXDlRj46O-Oyv36up-WYvywtvYguSI4rXeoVV-ZjAkyn8J4jBgija5K0YYP3fiYpwox5Qk8ESGcj-GK0" alt /></p>
<h2 id="heading-example">Example</h2>
<p>Now, let us look at an example where we will use the <code>post()</code> method. Here, we will <code>post()</code> the progress of some long running operation in the main thread which will update the UI. This is similar to how we used to update UI inside <code>AsyncTask</code>'s <code>onProgressUpdate</code>. As <code>AsyncTask</code> is now deprecated, this is a suitable alternative.</p>
<p>First, let us update the <code>ThreadWithLongRunningOperation</code> class as below</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadWithLongRunningOperation</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Consumer&lt;Integer&gt; mOnThreadProgressConsumer;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ThreadWithLongRunningOperation</span><span class="hljs-params">(Consumer&lt;Integer&gt; onThreadProgressConsumer)</span> </span>{
        <span class="hljs-keyword">this</span>.mOnThreadProgressConsumer = onThreadProgressConsumer;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Dummy sleep value to show work is happening</span>
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> SLEEP_TIME_MS = <span class="hljs-number">1000</span>;

        <span class="hljs-comment">// Create a handler using the Main thread looper</span>
        Handler mainThreadHandler = <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper());

        <span class="hljs-comment">// Post to the main handler; this will run the Runnable code block in UI thread</span>
        mainThreadHandler.post(() -&gt; mOnThreadProgressConsumer.accept(<span class="hljs-number">0</span>));

        <span class="hljs-comment">// Some long-running operation; using sleep to simulate the same</span>
        trySleep(SLEEP_TIME_MS);

        <span class="hljs-comment">// Post intermediate progress to UI</span>
        mainThreadHandler.post(() -&gt; mOnThreadProgressConsumer.accept(<span class="hljs-number">50</span>));

        <span class="hljs-comment">// Continue operation; using sleep to simulate the same</span>
        trySleep(SLEEP_TIME_MS);

        <span class="hljs-comment">// Update UI to show completion</span>
        mainThreadHandler.post(() -&gt; mOnThreadProgressConsumer.accept(<span class="hljs-number">100</span>));
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">trySleep</span><span class="hljs-params">(<span class="hljs-keyword">long</span> millis)</span> </span>{
        <span class="hljs-keyword">try</span> {
            sleep(millis);
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            <span class="hljs-comment">// do nothing</span>
        }
    }
}
</code></pre>
<blockquote>
<p>Note: If you want to learn about the <code>Consumer</code> interface, I have posted an article <a target="_blank" href="https://blog.sajalrg.com/consumer-interface-in-java">here</a>.</p>
</blockquote>
<p>In the <code>activity_main.xml</code> layout we will use the <code>TextView</code> to show the progress:</p>
<pre><code class="lang-xml">    <span class="hljs-tag">&lt;<span class="hljs-name">TextView</span>
        <span class="hljs-attr">android:id</span>=<span class="hljs-string">"@+id/counter_tv"</span>
        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">"wrap_content"</span>
        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">"wrap_content"</span>
        <span class="hljs-attr">android:text</span>=<span class="hljs-string">"0"</span>
        <span class="hljs-attr">app:layout_constraintBottom_toBottomOf</span>=<span class="hljs-string">"parent"</span>
        <span class="hljs-attr">app:layout_constraintEnd_toEndOf</span>=<span class="hljs-string">"parent"</span>
        <span class="hljs-attr">app:layout_constraintStart_toStartOf</span>=<span class="hljs-string">"parent"</span>
        <span class="hljs-attr">app:layout_constraintTop_toTopOf</span>=<span class="hljs-string">"parent"</span> /&gt;</span>
</code></pre>
<p>Finally, in our <code>MainActivity.java</code>, we will start the <code>Thread</code> and consume the update as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AppCompatActivity</span> </span>{

    TextView mCounterTextView;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(<span class="hljs-meta">@Nullable</span> Bundle savedInstanceState)</span> </span>{
        <span class="hljs-keyword">super</span>.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCounterTextView = findViewById(R.id.counter_tv);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>.onResume();
        ThreadWithLongRunningOperation threadWithLongRunningOperation
                = <span class="hljs-keyword">new</span> ThreadWithLongRunningOperation(
                        (progress) -&gt; mCounterTextView.setText(String.valueOf(progress))
        );
        threadWithLongRunningOperation.start();
    }
}
</code></pre>
<h3 id="heading-example-explanation">Example explanation</h3>
<p>The provided code features a custom thread, <code>ThreadWithLongRunningOperation</code>, which executes a simulated long-running operation and communicates progress updates to the UI thread through a <code>Handler</code>. The <code>Handler</code>, associated with the main thread's <code>Looper</code>, posts UI updates using the <code>post()</code> method to be executed inside the <code>UIThread</code>.</p>
<p>In the MainActivity, an instance of this custom thread is created and started in the <code>onResume</code> method, with progress updates displayed in a <code>TextView</code>. The Handler ensures proper communication between the background thread and the UI thread, allowing smooth progress updates in response to the long-running operation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we examined how <code>Message</code> gets added to the <code>MessageQueue</code> inside the <code>Handler</code> class. We explored how <code>Runnable</code> objects are converted to <code>Message</code> and saw an example of using the <code>post()</code> method to update the UI thread from another background thread.</p>
<p>In the next article, we will continue our exploration of the <code>Handler</code> class and delve into the usage of the <code>sendMessage()</code> and <code>handleMessage()</code> methods.</p>
<p>Stay tuned for more insights into effective handler usage in Android development!</p>
]]></content:encoded></item><item><title><![CDATA[Looper, Handler in Android Part 2 - Handler]]></title><description><![CDATA[This article is a continuation of our exploration into the Android's Looper and Handler. If you haven't read part 1 yet, I recommend revisiting it, as we won't be revisiting those concepts here. In this post, we will look at Handler class and its rel...]]></description><link>https://blog.sajalrg.com/looper-handler-in-android-part-2-handler</link><guid isPermaLink="true">https://blog.sajalrg.com/looper-handler-in-android-part-2-handler</guid><category><![CDATA[looper-android]]></category><category><![CDATA[handler-android]]></category><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android development]]></category><category><![CDATA[android internals]]></category><category><![CDATA[aosp]]></category><category><![CDATA[Java]]></category><category><![CDATA[constructors]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Tue, 16 Jan 2024 03:30:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705422953600/4d095c8f-4ee9-4f9c-bb1b-f243c8952bc5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is a continuation of our exploration into the Android's Looper and Handler. If you haven't read <a target="_blank" href="https://blog.sajalrg.com/looper-handler-in-android-part-1-looper">part 1</a> yet, I recommend revisiting it, as we won't be revisiting those concepts here. In this post, we will look at <code>Handler</code> class and its relationship with <code>Looper</code> and <code>Message</code> classes.</p>
<h2 id="heading-construction-of-handler">Construction of Handler</h2>
<p>Just as <code>Looper</code> in Android is linked to a single thread, it's important to note that a <code>Handler</code> is similarly tied to a single <code>Looper</code>. However, unlike the <code>Looper</code> you can create multiple objects of the <code>Handler</code> class within the same thread.</p>
<p>Application developers have two constructors at their disposal for creating a new Handler class:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span> <span class="hljs-params">(Looper looper)</span>
<span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span> <span class="hljs-params">(Looper looper, Handler.Callback callback)</span></span>
</code></pre>
<blockquote>
<p>Note: Two additional public constructors, <code>public Handler()</code> and <code>public Handler(Handler.Callback callback)</code>, are now deprecated. If you encounter these constructors or choose to use them for some reason, be aware that they internally use the looper obtained via the <code>Looper.myLooper()</code> method.</p>
</blockquote>
<p>Here is the actual constructor of the handler, not accessible to app developers. I'm presenting it here to shed light on the inner workings of the handler:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Handler</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Looper looper, <span class="hljs-meta">@Nullable</span> Callback callback, <span class="hljs-keyword">boolean</span> async, <span class="hljs-keyword">boolean</span> shared)</span> </span>{
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
    mIsShared = shared;
}
</code></pre>
<blockquote>
<p>Note: This multipart article won't cover the details of <code>mAsynchronous</code> and <code>mIsShared</code>.</p>
</blockquote>
<h2 id="heading-message-and-callback-classes">Message and Callback classes</h2>
<p>Before comprehending the role of the Handler, let us examine the definitions of the <code>Handler.Callback</code> and <code>Message</code> classes</p>
<h3 id="heading-1-handlercallback">1. <code>Handler.Callback</code></h3>
<p>The <code>Callback</code> interface is defined inside <code>Handler</code> class as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Callback</span> </span>{
    <span class="hljs-comment">/**
    * <span class="hljs-doctag">@param</span> msg A {<span class="hljs-doctag">@link</span> android.os.Message Message} object
    * <span class="hljs-doctag">@return</span> True if no further handling is desired
    */</span>
    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">handleMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message msg)</span></span>;
}
</code></pre>
<h3 id="heading-2-message">2. <code>Message</code></h3>
<p>The <a target="_blank" href="https://developer.android.com/reference/android/os/Message"><code>Message</code></a> class has various fields and methods, but for our use case we'll focus on a subset of those:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Message</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Parcelable</span> </span>{
    <span class="hljs-comment">/**
     * User-defined message code so that the recipient can identify
     * what this message is about. Each {<span class="hljs-doctag">@link</span> Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> what;

    <span class="hljs-comment">/**
     * arg1 and arg2 are lower-cost alternatives to using
     * {<span class="hljs-doctag">@link</span> #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> arg1;

    <span class="hljs-comment">/**
     * arg1 and arg2 are lower-cost alternatives to using
     * {<span class="hljs-doctag">@link</span> #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> arg2;

    <span class="hljs-comment">/**
     * An arbitrary object to send to the recipient.  When using
     * {<span class="hljs-doctag">@link</span> Messenger} to send the message across processes this can only
     * be non-null if it contains a Parcelable of a framework class (not one
     * implemented by the application).   For other data transfer use
     * {<span class="hljs-doctag">@link</span> #setData}.
     *
     * &lt;p&gt;Note that Parcelable objects here are not supported prior to
     * the {<span class="hljs-doctag">@link</span> android.os.Build.VERSION_CODES#FROYO} release.
     */</span>
    <span class="hljs-keyword">public</span> Object obj;

    <span class="hljs-meta">@UnsupportedAppUsage</span>
    <span class="hljs-comment">/*package*/</span> Handler target;

    <span class="hljs-meta">@UnsupportedAppUsage</span>
    <span class="hljs-comment">/*package*/</span> Runnable callback;
}
</code></pre>
<h2 id="heading-relationship-between-handler-message-and-looper">Relationship between Handler, Message and Looper</h2>
<p>Handler is used to interact with the <code>Message</code> loop i.e. <code>Looper.loop()</code>.</p>
<p>In <a target="_blank" href="https://blog.sajalrg.com/looper-handler-in-android-part-1-looper">part 1</a>, we delved into a high-level understanding of the <code>Looper.loop()</code> method. Now, let's take a close look at the implementation of this method.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">loop</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">final</span> Looper me = myLooper();
    <span class="hljs-keyword">if</span> (me == <span class="hljs-keyword">null</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"No Looper; Looper.prepare() wasn't called on this thread."</span>);
    }
    <span class="hljs-comment">/* &lt;&lt; unrelated code removed for comprehension &gt;&gt; */</span>
    <span class="hljs-keyword">for</span> (;;) {
        <span class="hljs-keyword">if</span> (!loopOnce(me, ident, thresholdOverride)) {
            <span class="hljs-keyword">return</span>;
        }
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">loopOnce</span><span class="hljs-params">(<span class="hljs-keyword">final</span> Looper me, <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> ident, <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> thresholdOverride)</span> </span>{
    Message msg = me.mQueue.next(); <span class="hljs-comment">// might block</span>
    <span class="hljs-keyword">if</span> (msg == <span class="hljs-keyword">null</span>) {
        <span class="hljs-comment">// No message indicates that the message queue is quitting.</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
    <span class="hljs-comment">/* &lt;&lt; unrelated code removed for comprehension &gt;&gt; */</span>
    <span class="hljs-keyword">try</span> {
        msg.target.dispatchMessage(msg);
        <span class="hljs-keyword">if</span> (observer != <span class="hljs-keyword">null</span>) {
            observer.messageDispatched(token, msg);
        }
        dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : <span class="hljs-number">0</span>;
    } <span class="hljs-keyword">catch</span> (Exception exception) {
        <span class="hljs-comment">/* &lt;&lt; unrelated code removed for comprehension &gt;&gt; */</span>
        <span class="hljs-keyword">throw</span> exception;
    }
    <span class="hljs-comment">/* &lt;&lt; unrelated code removed for comprehension &gt;&gt; */</span>
}
</code></pre>
<blockquote>
<p>Note: I've included only the essential code for our comprehension, but you can refer to the complete code <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/os/Looper.java">here</a>.</p>
</blockquote>
<p>Here, <code>msg.target</code> has reference to the instance of the <code>Handler</code> class and the <code>Looper</code> calls the <code>dispatchMessage()</code> method of the <code>Handler</code> class in each loop. This occurs inside the <code>Thread</code> where the <code>Looper</code> is looping.
Same can be visualised in below sequence diagram
<img src="https://www.plantuml.com/plantuml/svg/RP11ReGm34NtFeMNiE02Q8HcsKhjebBd05RYTY914YLErTw-eG6BYjd44BxVmxvceIHbcI7MweoBv0LlcHF074A4btfmmc72LywPFlcjSE4HFNzBrmCPSLyaZ2sdx__I0BVS64_axSnfnCi5JU8rU6zNs3L2ZzEab3qFMyMXCbRMY8cb98_EPo5l-6o88Qy_g9qwm56-jAkZSu_1Ld5GgcgVToie_hGWilOz_3rtsuSU3ed6RJFlM5NhrWzcwt8aCVSjKqTxE5jj-mXfmRMVn0KFba_hj9mbXH_riRS0rtgMPVu5" alt="uml sequence diagram of looper.loop method" /></p>
<p>By now, we've covered <code>Looper</code>, <code>Handler</code>, and the <code>Message</code> class and have an understanding of the role of the <code>MessageQueue</code>.</p>
<p>In the upcoming article, we will consolidate our knowledge gained so far and apply it in real-world scenarios to effectively utilize the <code>Handler</code> class. Additionally, we will closely examine the <code>dispatchMessage()</code> method to deepen our understanding of its role in the overall process.</p>
]]></content:encoded></item><item><title><![CDATA[Looper, Handler in Android Part 1 - Looper]]></title><description><![CDATA[In this series of articles, we'll delve into the multi-threading concept of Android, exploring the roles of classes Thread, Looper, and Handler.
A Thread can be seen as a lightweight process, enabling the execution of multiple operations in parallel....]]></description><link>https://blog.sajalrg.com/looper-handler-in-android-part-1-looper</link><guid isPermaLink="true">https://blog.sajalrg.com/looper-handler-in-android-part-1-looper</guid><category><![CDATA[Android]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[Threading]]></category><category><![CDATA[thread]]></category><category><![CDATA[Threads]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Fri, 12 Jan 2024 04:02:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/axpnYPca2Ug/upload/89b5f0a0ed47a99d761f26f69846c1e8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this series of articles, we'll delve into the multi-threading concept of Android, exploring the roles of classes Thread, Looper, and Handler.</p>
<p>A Thread can be seen as a lightweight process, enabling the execution of multiple operations in parallel. However, our focus in this article will shift towards <a target="_blank" href="https://developer.android.com/reference/android/os/Looper"><code>Looper</code></a>, <a target="_blank" href="https://developer.android.com/reference/android/os/Handler"><code>Handler</code></a> classes in Android and understanding their relationship with Thread. More information on Thread can be found <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html">here</a>.</p>
<p>In Android, your application/activity will inherently possess at least one Thread, known as the MainThread. Android generally prefers abstracting the underlying thread and instead encourages the use of android classes like <code>Handler</code>.</p>
<p>A <code>Looper</code> in Android is associated with a single thread. If you've worked in Android, you might have come across methods like <code>Looper.getMainLooper()</code> or <code>Looper.myLooper()</code>. In this article, we will deep dive into those and try to understand what they do. Later, we will link this concept to <code>Handler</code> and <a target="_blank" href="https://developer.android.com/reference/android/os/MessageQueue"><code>MessageQueue</code></a>.</p>
<h3 id="heading-construction-of-a-looper">Construction of a Looper.</h3>
<p>As the Looper constructor is private, the only way to create a Looper is by invoking Looper.prepare().</p>
<p>However, if you try to call this inside you activity like below it will crash your application.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">super</span>.onResume();
    <span class="hljs-comment">// This will crash with Runtime exception "Only one Looper may be created per thread"</span>
    Looper.prepare();
}
</code></pre>
<p>When examining the logcat logs for the crash, the stack trace will appear as follows:</p>
<pre><code>Caused by: java.lang.RuntimeException: Only one Looper may be created per thread
    at android.os.Looper.prepare(Looper.java:<span class="hljs-number">109</span>)
    at android.os.Looper.prepare(Looper.java:<span class="hljs-number">104</span>)
    at com.sajalrg.looperhandlerandroid.MainActivity.onResume(MainActivity.java:<span class="hljs-number">20</span>)
</code></pre><p>The crash is attributed to the constraint of allowing only one Looper object per thread. As previously explained, your Activity operates on the <code>Thread</code> known as the <code>MainThread</code>, which already has an associated <code>Looper</code>.</p>
<p>Hence, to create a new Looper, you need to define a new <code>Thread</code>. Let's do that.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyLooperThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// calling Looper.prepare() inside thread once will not crash and creates new Looper object</span>
        Looper.prepare();
    }
}
</code></pre>
<p>Now, you can create new Looper instance by starting the Thread.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">super</span>.onResume();
    MyLooperThread myLooperThread = <span class="hljs-keyword">new</span> MyLooperThread();
    <span class="hljs-comment">// this will start new thread and call the run() method of thread</span>
    myLooperThread.start();
}
</code></pre>
<p>Please be aware not to conflate <code>myLooperThread.start()</code> with <code>myLooperThread.run()</code>. In this context, invoking the <code>run()</code> method will not initiate the thread; instead, it merely executes the <code>run()</code> method within the same thread. To commence a new thread and internally trigger the run() method within the new thread, it is imperative to use the <code>myLooperThread.start()</code> method.</p>
<p>To obtain the existing Looper instance for a specific thread, you can call the <code>Looper.myLooper()</code> method in the thread. This function returns the Looper instance associated with the thread, if one exists. To obtain an instance of the Looper for the MainThread, you can call <code>Looper.getMainLooper()</code> from <strong>any</strong> thread, and it will consistently return the Looper associated with the <code>MainThread</code>.</p>
<h3 id="heading-working-with-looper">Working with Looper</h3>
<p>Although we have successfully created a Looper object, our class currently serves no significant purpose. To understand its utility, let's examine another method, <code>Looper.loop()</code>.</p>
<p>As the name suggests, this method runs an infinite <strong>loop</strong>, implying that your thread will never exit. Let's use it in our <code>MyLooperThread</code> class.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyLooperThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Thread</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyLooperThread</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// lets give our thread name so we can identify it in ps output</span>
        <span class="hljs-keyword">super</span>(<span class="hljs-string">"MyLooperThread"</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// calling Looper.prepare() inside thread once will not crash and creates new Looper object</span>
        Looper.prepare();
        Log.d(<span class="hljs-string">"MyLooperThread "</span>, <span class="hljs-string">"run(): after Looper.prepare()"</span>);
        Looper.loop();
        Log.d(<span class="hljs-string">"MyLooperThread "</span>, <span class="hljs-string">"run(): after Looper.loop()"</span>);
    }
}
</code></pre>
<p>Upon running the code, you'll notice that "run(): after Looper.loop()" is never printed. You can also confirm that your thread is running by executing below shell command</p>
<pre><code class="lang-bash">adb shell ps -T | grep <span class="hljs-string">"MyLooperThread"</span>
</code></pre>
<p>It's crucial to note that executing the above shell command without the inclusion of <code>Looper.loop()</code> will result in no output. This is because the thread would have terminated after the invocation of <code>Looper.prepare()</code>.</p>
<p>Now, before taking a closer look at <code>Looper</code> and the <code>loop()</code>, let's examine the constructor of Looper.</p>
<pre><code class="lang-java">    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Looper</span><span class="hljs-params">(<span class="hljs-keyword">boolean</span> quitAllowed)</span> </span>{
        mQueue = <span class="hljs-keyword">new</span> MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }
</code></pre>
<p>The Looper constructor comprises a <code>MessageQueue</code>. As the name implies, the <code>MessageQueue</code> is a queue of <code>Messages</code>. We will dig deeper into <code>MessageQueue</code> and <code>Messages</code> in subsequent articles. For now, let's continue examination of the <code>loop()</code> method.</p>
<p>The <code>loop()</code> method iterates indefinitely through the <code>MessageQueue</code>, performing operations if any messages are present. This perpetual execution takes place within the same thread where the Looper is actively looping.</p>
<p>Although we haven't delved deeply into <code>Message</code> yet, the primary focus of this post was to provide an introduction to the <code>Looper</code>. I assume you now have a high-level understanding of what the Looper is, how it is created, and its usage. If you still have any lingering questions or uncertainties regarding the Looper, feel free to ask in the comments.</p>
<p>In the subsequent post, we will explore <code>Message</code> and <code>Handler</code> in greater detail. Stay tuned for a more in-depth discussion on these concepts.</p>
]]></content:encoded></item><item><title><![CDATA[Consumer interface in Java]]></title><description><![CDATA[The Consumer interface was introduced in Java 1.8. Below is a an excerpt from the official documentation

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expecte...]]></description><link>https://blog.sajalrg.com/consumer-interface-in-java</link><guid isPermaLink="true">https://blog.sajalrg.com/consumer-interface-in-java</guid><category><![CDATA[consumer java]]></category><category><![CDATA[Java]]></category><category><![CDATA[functional interface]]></category><category><![CDATA[Lambda Expression]]></category><category><![CDATA[java8]]></category><category><![CDATA[java 8]]></category><category><![CDATA[java, java8, programming, code, coding, beginner, stream api, api, ]]></category><category><![CDATA[Java, Java 8, Java SE, Java EE, JavaFX,]]></category><category><![CDATA[Java, Advanced features, Generics, Annotations, Lambda expressions, Stream API, Date and Time API, Modules, Complex applications,]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Sun, 31 Dec 2023 10:28:35 GMT</pubDate><content:encoded><![CDATA[<p>The <code>Consumer</code> interface was introduced in Java 1.8. Below is a an excerpt from the official <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html">documentation</a></p>
<blockquote>
<p>Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.</p>
</blockquote>
<p>I want to talk about the <code>Consumer</code> functional interface in this article because I find it very useful and use it often.</p>
<h2 id="heading-consumer-definition">Consumer definition</h2>
<p><code>Consumer</code> is an interface with as single abstract method <code>accept(T t)</code>.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Consumer</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">accept</span><span class="hljs-params">(T t)</span></span>;
}
</code></pre>
<p>The <code>accept</code> method, as its name suggests, "consumes" a value and performs a specific operation on it.</p>
<h2 id="heading-uses-of-consumer-interface">Uses of Consumer interface</h2>
<ol>
<li>The behavior (accept method) of the consumer interface is well known. As a result, it increases the readability of the code.</li>
<li>Enhances code reusability by leveraging pre-existing interfaces rather than creating custom ones for the same behavior.</li>
<li>As it is a <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html">functional interface</a>, it can be efficiently defined using lambda expressions.</li>
<li>The <code>Consumer</code> interface is commonly utilized in many new Java methods, such as those found in the <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html"><code>Stream</code></a> class.</li>
<li>The <code>Consumer</code> instances can be executed sequentially by utilizing the <code>andThen</code> method.</li>
</ol>
<h2 id="heading-example-of-consumer-interface">Example of Consumer interface</h2>
<p>Let us view some examples of <code>Consumer</code> interface. To gauge its usability, we will first try to solve the problem without <code>Consumer</code> interface.</p>
<p><strong>Problem Statement</strong>
Let us consider a class <code>PerformLongOperation</code> which is doing some complex operation and keeps posting progress of its update to the listener. The listener needs to be passed as a parameter of <code>doTask</code> function which perform the actual task.</p>
<p><strong>Solution 1</strong>: Using interface
Here, we will use <code>IOnTaskUpdateCallback</code> interface to define the callback contract. Below will be one solution</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PerformLongOperation</span> </span>{
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doTask</span><span class="hljs-params">(IOnTaskUpdateCallback onTaskUpdatedCallback)</span> </span>{
            onTaskUpdatedCallback.onProgressUpdated(<span class="hljs-number">0</span>);
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">10</span>; i &lt;= <span class="hljs-number">100</span>; i+=<span class="hljs-number">10</span>) {
                <span class="hljs-keyword">try</span> {
                    <span class="hljs-comment">// add sleep to show task is being done</span>
                    Thread.sleep(<span class="hljs-number">1000</span>);
                } <span class="hljs-keyword">catch</span> (InterruptedException exp) {
                    <span class="hljs-comment">// ignoring for now</span>
                }
                onTaskUpdatedCallback.onProgressUpdated(i);
            }
        }
    }

    <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IOnTaskUpdateCallback</span> </span>{
        <span class="hljs-comment">// called when any update in the progress</span>
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">onProgressUpdated</span><span class="hljs-params">(<span class="hljs-keyword">int</span> progress)</span></span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        PerformLongOperation longGoing = <span class="hljs-keyword">new</span> PerformLongOperation();
        longGoing.doTask(<span class="hljs-keyword">new</span> IOnTaskUpdateCallback() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onProgressUpdated</span><span class="hljs-params">(<span class="hljs-keyword">int</span> progress)</span> </span>{
                System.out.println(<span class="hljs-string">"Progress is: "</span> + progress);
            }
        });
    }
}
</code></pre>
<p><strong>Solution 1.1</strong>: Using interface and lambda
We can make our <code>main()</code> method more concise by using lambda like below</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
    PerformLongOperation longGoing = <span class="hljs-keyword">new</span> PerformLongOperation();
    longGoing.doTask(progress -&gt; System.out.println(<span class="hljs-string">"Progress is: "</span> + progress));
}
</code></pre>
<p><strong>Solution 2</strong>: Using Consumer
Since, <code>IOnTaskUpdateCallback</code> satisfies all condition for being a Consumer, we can just use <code>Consumer</code> rather than defining a new one new interface.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PerformLongOperation</span> </span>{
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doTask</span><span class="hljs-params">(Consumer&lt;Integer&gt; onTaskUpdatedCallback)</span> </span>{
            onTaskUpdatedCallback.accept(<span class="hljs-number">0</span>);
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">10</span>; i &lt;= <span class="hljs-number">100</span>; i+=<span class="hljs-number">10</span>) {
                <span class="hljs-keyword">try</span> {
                    <span class="hljs-comment">// add sleep to show task is being done</span>
                    Thread.sleep(<span class="hljs-number">1000</span>);
                } <span class="hljs-keyword">catch</span> (InterruptedException exp) {
                    <span class="hljs-comment">// ignoring for now</span>
                }
                onTaskUpdatedCallback.accept(i);
            }
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        PerformLongOperation longGoing = <span class="hljs-keyword">new</span> PerformLongOperation();
        longGoing.doTask(progress -&gt; System.out.println(<span class="hljs-string">"Progress is: "</span> + progress));
    }
}
</code></pre>
<p>To sum up, the Consumer functional interface in Java simplifies coding, enhances reusability, and streamlines development, making it a valuable tool for efficient programming.</p>
]]></content:encoded></item><item><title><![CDATA[Activity in Android - Part 1]]></title><description><![CDATA[Merriam Webster dictionary defines activity as

the quality or state of being active : behavior or actions of a particular kind

In a nutshell, Activity refers to place of interaction with an Android device. Technically, it represents a Window, but t...]]></description><link>https://blog.sajalrg.com/activity-in-android-part-1</link><guid isPermaLink="true">https://blog.sajalrg.com/activity-in-android-part-1</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><category><![CDATA[android apps]]></category><category><![CDATA[android development]]></category><category><![CDATA[Activity]]></category><category><![CDATA[Activities, Android, ActivityLifecycle]]></category><category><![CDATA[software development]]></category><category><![CDATA[#windows #doors #architecture #window #pc #linux #technology #interiordesign #design #computer #microsoft #doorsandwindows #tech #home #laptop #software #photography #android #apple #bhfyp #construction #building]]></category><dc:creator><![CDATA[Sajal Raj Gautam]]></dc:creator><pubDate>Fri, 29 Dec 2023 08:24:19 GMT</pubDate><content:encoded><![CDATA[<p>Merriam Webster dictionary <a target="_blank" href="https://www.merriam-webster.com/dictionary/activity">defines activity</a> as</p>
<blockquote>
<p>the quality or state of being active : behavior or actions of a particular kind</p>
</blockquote>
<p>In a nutshell, <a target="_blank" href="https://developer.android.com/reference/android/app/Activity">Activity</a> refers to place of interaction with an Android device. Technically, it represents a <a target="_blank" href="https://developer.android.com/reference/android/view/Window">Window</a>, but the Android takes care of creating the window for us, eliminating the need for direct interaction with it's methods.</p>
<p>This post will focus exclusively on discussing the activity and its lifecycle. It is assumed that you already have a basic understanding of writing Android applications, and it is not intended as an introductory guide to Android development.</p>
<h2 id="heading-size-of-an-activity">Size of an Activity</h2>
<p>In Android, an application can contain multiple activities. It is not necessary for an activity to occupy the full screen. It can be displayed as a floating window, embedded into another window, or used in <a target="_blank" href="https://developer.android.com/guide/topics/ui/multi-window">multi-window mode</a>. Therefore, careful consideration is required when deciding whether to create a new activity or not. Android's <a target="_blank" href="https://developer.android.com/reference/android/app/Activity">official definition</a> serves as a guide in this context.</p>
<blockquote>
<p>An activity is a single, focused thing that the user can do.</p>
</blockquote>
<p>In other words, if your activity is like a floating window, all the actions you want the user to perform within that window should be part of the same activity, without requiring them to switch to another window.</p>
<h2 id="heading-definition-of-an-activity">Definition of an Activity</h2>
<p>In Android, we define an Activity rather than create it. The creation and management of an Activity are handled by the Android system itself. Unlike in java there is no <code>public static void main(String[] args)</code> function inside Activity class. It is actually defined inside the <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/core/java/android/app/ActivityThread.java">ActivityThread</a>. The reason is that there is a lot of activity happening in the background to make your activity visible and interactive. Therefore, all those parts are abstracted away by Android Frameworks.</p>
<p>For end users, if they want to create an activity, they have to define it in two places.</p>
<h3 id="heading-1-registration-in-manifest">1. Registration in manifest</h3>
<p>As you may be aware, <a target="_blank" href="https://developer.android.com/guide/topics/manifest/manifest-intro">AndroidManifest.xml</a> is a crucial file in any Android project. It serves as a manifesto for your application, informing the Android framework about its various aspects. This file can be accessed by anyone who has the APK file, and Android OS heavily relies on it to understand the details of your application. You can also check the same with following <a target="_blank" href="https://developer.android.com/tools/aapt2#dump_commands">command</a></p>
<pre><code class="lang-bash">aapt dump badging &lt;you-apk-name&gt;.apk
</code></pre>
<p>The AndroidManifest is also where you define certain attributes of your <a target="_blank" href="https://developer.android.com/guide/topics/manifest/activity-element">activity</a> (lower case). Below is one example of the <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:development/samples/Compass/AndroidManifest.xml">Compass</a> application from Android samples</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- This file describes the code in the Compass package, which is
     used by the system to determine how to start your application and
     integrate it with the rest of the system.  --&gt;</span>

<span class="hljs-comment">&lt;!-- Declare the contents of this Android application.  The namespace
     attribute brings in the Android platform namespace, and the package
     supplies a unique name for the application.  When writing your
     own application, the package name must be changed from "com.example.*"
     to come from a domain that you own or have control over. --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">manifest</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">"http://schemas.android.com/apk/res/android"</span>
    <span class="hljs-attr">package</span>=<span class="hljs-string">"com.example.android.compass"</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- This package contains an application...  The 'label' is the name
         to display to the user for the overall application, and provides
         a default label for all following components.  The syntax here is a
         reference to one of our string resources.--&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">application</span> <span class="hljs-attr">android:label</span>=<span class="hljs-string">"@string/compass_app"</span>&gt;</span>

        <span class="hljs-comment">&lt;!-- An Activity in the application - this is something the user
             can launch and interact with.  The "name" attribute is the
             name of the class within your package that implements this
             activity. --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">activity</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"CompassActivity"</span>&gt;</span>

            <span class="hljs-comment">&lt;!-- An IntentFilter tells the system when it should use your
                 activity.  This allows the user to get to your activity
                 without someone having to explicitly know to launch your
                 class "com.example.android.compass_app.CompassActivity". --&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">intent-filter</span>&gt;</span>
                <span class="hljs-comment">&lt;!-- The MAIN action describes a main entry point into an
                     activity, without any associated data. --&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.action.MAIN"</span> /&gt;</span>

                <span class="hljs-comment">&lt;!-- This places this activity into the main app list. --&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">"android.intent.category.LAUNCHER"</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">intent-filter</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">activity</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">application</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">manifest</span>&gt;</span>
</code></pre>
<p>Here, we are declaring <code>CompassActivity</code> in our application manifest. The <code>intent-filter</code> is used to instruct Android to display our activity in the application list that the user sees. If you remove this intent filter, your activity will no longer be visible in the app list, even if your APK is installed.</p>
<h3 id="heading-2-class-definition">2. Class definition</h3>
<p>In the first part, we declared in the manifest that there is a <code>CompassActivity</code> class in the package <code>com. example. android. compass</code>. Let's explore same.</p>
<p>An Activity, an android always extends the <a target="_blank" href="https://developer.android.com/reference/android/app/Activity">Activity</a> class. There are a few derived classes that internally extend the Activity class but provide additional methods to support specific use cases. Depending on the requirements, you can choose to extend any of those as well, eg <a target="_blank" href="https://developer.android.com/reference/androidx/fragment/app/FragmentActivity">FragmentActivity</a>, <a target="_blank" href="https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity">AppCompatActivity</a>, <a target="_blank" href="developer.android.com/reference/android/preference/PreferenceActivity">PreferenceActivity</a> (deprecated in API level 29).</p>
<p>In the sample code, <a target="_blank" href="https://cs.android.com/android/platform/superproject/main/+/main:development/samples/Compass/src/com/example/android/compass/CompassActivity.java;bpv=0;bpt=0">CompassActivity</a> is defined like below.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example.android.compass;
<span class="hljs-comment">// import statements</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CompassActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Activity</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Renderer</span>, <span class="hljs-title">SensorEventListener</span> </span>{
    <span class="hljs-comment">// implementations</span>
}
</code></pre>
<hr />
<p>Now that we understand how to define an Activity, let's go over how Android loads your layout in the window in the next part.</p>
]]></content:encoded></item></channel></rss>