<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chiu on Medium]]></title>
        <description><![CDATA[Stories by Chiu on Medium]]></description>
        <link>https://medium.com/@yozyyyqls?source=rss-2c847649d308------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UlBaZhj_aZxPzeEG</url>
            <title>Stories by Chiu on Medium</title>
            <link>https://medium.com/@yozyyyqls?source=rss-2c847649d308------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:42:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yozyyyqls/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Event-Dispatching in Android (2) — Click Listener]]></title>
            <link>https://medium.com/@yozyyyqls/event-dispatching-in-android-2-click-listener-cb011afc2495?source=rss-2c847649d308------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb011afc2495</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Chiu]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 12:27:23 GMT</pubDate>
            <atom:updated>2024-09-01T00:37:54.349Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Event-Dispatching in Android (2) — Click Listener</em></strong></h3><h3><em>Introduction</em></h3><p>Sometimes we set up a click listener, long click listener, or touch listener when using View or ViewGroup in Android Development. But do you ever think about <strong>where they take effect? Do these listeners have any impact on each other</strong>?</p><p>First of all, the OnClickListener, OnLongClickListener, and OnTouchListener all are defined in View.</p><pre>public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {<br><br> public interface OnTouchListener {<br>   boolean onTouch(View v, MotionEvent event);<br> }<br><br> public interface OnClickListener {<br>      void onClick(View v);<br> }<br><br> public interface OnLongClickListener {<br>      boolean onLongClick(View v);<br> }<br>}</pre><h3><em>OnClickListener</em></h3><p>We have been familiar with using the click listener. <strong>But what is a click event? How is the Android System aware of the click event happening?</strong></p><p>Here is the source code of onTouchEvent() in View. Now we can answer the question.</p><p><strong>1. What’s a click event?</strong></p><p>The click event is a composite of touch events. When the view gets a DOWN and UP action, we consider it to be a click event. No matter how many MOVE actions we get.</p><p><strong>2. How does the Android know the click event happening?</strong></p><p>As the view decides to deal with the touch event, all the events will be dispatched to the onTouchEvent() method. The view takes UP action. then it knows the click event happens.</p><pre>public boolean onTouchEvent(MotionEvent event) {<br>    // ...<br>    if (clickable || (viewFlags &amp; TOOLTIP) == TOOLTIP) {<br>        switch (action) {<br>            case MotionEvent.ACTION_UP:<br>             // ...<br>                // Only perform take click actions if we were in the pressed state<br>                if (!focusTaken) {<br>                    // Use a Runnable and post this rather than calling<br>                    // performClick directly. This lets other visual state<br>                    // of the view update before click actions start.<br>                    if (mPerformClick == null) {<br>                        mPerformClick = new PerformClick();<br>                    }<br>                    if (!post(mPerformClick)) {<br>                        performClickInternal();<br>                    }<br>                }<br>            // ...<br>        }<br>        return true;<br>    }<br>    return false;<br>}</pre><p>We can also get the extra information as follows.</p><ol><li>The onClick() method will be invoked when the View gets the UP action. Even though received the MOVE action before the UP action.</li><li>If the view cannot take focused, the onClick() method won’t be invoked.</li><li>If the view is not clickable and not a tooltip (when hovering or long pressing, the tips of the tool appear), the onClick() method won’t be invoked.</li></ol><h3><em>OnLongClickListener</em></h3><p>It is very similar to the click event. As your intuition, the difference between a click event and a long click event is how long we press the view. This question comes along with how Android detects a long press.</p><p>When you’re pressing the View. At the time, the View checks if you trigger the long click by invoking the checkForLongClick() method. It will post a runnable for checking in the future. After the delay time, the runnable will be invoked. It checks the pressed state and executes the performLongClick() method, which finally invokes the OnLongClickListener.</p><p>You may be curious about what is the runnable for doing the checking work. The runnable is CheckForLongPress, the inner class of the View.</p><p>Here is the chain of invocation.</p><pre>OnLongClickListener::onLongClick<br>--&gt; View::performLongClickInternal<br>--&gt; View::performLongClick<br>--&gt; CheckForLongPress::run (CheckForLongPress implements the Runnable)<br>--&gt; View::checkForLongClick<br>--&gt; View::onTouchEvent</pre><p>If you’re interested in the source of long click. Keep reading. Else, skip them.</p><pre>private void checkForLongClick(long delay, float x, float y, int classification) {<br>    if ((mViewFlags &amp; LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags &amp; TOOLTIP) == TOOLTIP) {<br>        mHasPerformedLongPress = false;<br><br>        if (mPendingCheckForLongPress == null) {<br>            mPendingCheckForLongPress = new CheckForLongPress();<br>        }<br>        mPendingCheckForLongPress.setAnchor(x, y);<br>        mPendingCheckForLongPress.rememberWindowAttachCount();<br>        mPendingCheckForLongPress.rememberPressedState();<br>        mPendingCheckForLongPress.setClassification(classification);<br>        postDelayed(mPendingCheckForLongPress, delay);<br>    }<br>}</pre><p>We can get some info from the source code above.</p><ol><li>If you want to trigger the long click execution, the view must be long-clickable, or it is a tooltip view.</li><li>The mHasPerformedLongPress flag is a mark for executing the onLongClick() method. When consuming the UP, DOWN, and CANCEL actions, the flag will turn false. It turns true when finishing the onLongClick() method.</li><li>The checkForLongClick() method uses Handler to post a runnable for the delay time. How does the Android get the delay value? Let’s see the place where invoke the checkForLongClick() method.</li></ol><pre>checkForLongClick(<br> ViewConfiguration.getLongPressTimeout(),<br> x,<br> y,<br> TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS<br>);</pre><p>So we know the delay time is from the ViewConfiguration class.</p><p>You already know the difference between a single click and a long click as far. Do you ever think how they affect each other? If the onLongClick() method is performed, will the onClick() method be performed?</p><p>The answer is NO. You can see it clearly in the source code. As the mHasPerformedLongPress flag is true that means the onLongClick() is performed before, and the performClickInternal() won’t perform anymore.</p><pre>// View::onTouchEvent<br>switch (action) {  <br>    case MotionEvent.ACTION_UP:<br>     if (!mHasPerformedLongPress &amp;&amp; !mIgnoreNextUpEvent) {  <br>     // This is a tap, so remove the longpress check  <br>     removeLongPressCallback();  <br>   <br>     // Only perform take click actions if we were in the pressed state  <br>     if (!focusTaken) {  <br>         // Use a Runnable and post this rather than calling  <br>         // performClick directly. This lets other visual state        // of the view update before click actions start.        if (mPerformClick == null) {  <br>             mPerformClick = new PerformClick();  <br>         }  <br>         if (!post(mPerformClick)) {  <br>             performClickInternal();  <br>         }  <br>     }  <br>}</pre><h3><em>OnTouchListener</em></h3><p>Unlike the single click and long click, which are based on a composite of touch events, the OnTouchListener calls the onTouch() method on time when a touch event is dispatched. So here’s a priority.</p><pre>public boolean dispatchTouchEvent(MotionEvent event) {<br>    // ...<br>    if (onFilterTouchEventForSecurity(event)) {<br>        if ((mViewFlags &amp; ENABLED_MASK) == ENABLED &amp;&amp; handleScrollBarDragging(event)) {<br>            result = true;<br>        }<br>        //noinspection SimplifiableIfStatement<br>        ListenerInfo li = mListenerInfo;<br>        if (li != null &amp;&amp; li.mOnTouchListener != null<br>                &amp;&amp; (mViewFlags &amp; ENABLED_MASK) == ENABLED<br>                &amp;&amp; li.mOnTouchListener.onTouch(this, event)) {<br>            result = true; // &lt;--<br>        }<br><br>        if (!result &amp;&amp; onTouchEvent(event)) {<br>            result = true;<br>        }<br>    }<br>    // ...<br>    return result;<br>}</pre><h3><em>Summary</em></h3><ol><li><strong>OnClickListener</strong>: A click event is triggered by a combination of DOWN and UP touch actions, regardless of any MOVE actions. The onClick() method is invoked upon receiving the UP action if the view is clickable and can take focus. If the onLongClick() method is performed, the onClick() method won’t be performed.</li><li><strong>OnLongClickListener</strong>: A long-click event is detected by the checkForLongClick() method, which posts a runnable (CheckForLongPress) after a delay. The onLongClick() method is called if the view is long-clickable and remains pressed until the delay elapses.</li><li><strong>OnTouchListener</strong>: This listener has the highest priority and is invoked directly with each touch event. If onTouch() returns true, it prevents onClick() and onLongClick() from being executed, as the onTouchEvent() method won’t be invoked.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb011afc2495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Dispatching in Android (1)]]></title>
            <link>https://medium.com/@yozyyyqls/event-dispatching-in-android-1-01a3b2a966b4?source=rss-2c847649d308------2</link>
            <guid isPermaLink="false">https://medium.com/p/01a3b2a966b4</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chiu]]></dc:creator>
            <pubDate>Tue, 28 May 2024 06:54:03 GMT</pubDate>
            <atom:updated>2024-05-28T06:54:03.379Z</atom:updated>
            <content:encoded><![CDATA[<p>The blog is based on a real problem.</p><h3>1 Introduction</h3><p>When writing the sliding delete function, there is a problem that the sliding cannot be triggered in some position of the item. More information is followed</p><ol><li>This is a custom view that extends the RecyclerView. It names SwipeRecyclerView and supports swiping from right to left to pull out the delete menu.</li><li>The root view of every item in the SwipeRecyclerView is a FrameLayout. And the FrameLayout has serval child views.</li><li>The conditions that decide to trigger sliding delete are direction, distance, and speed of sliding. If it satisfies those three conditions, we’ll return true in the onInterceptTouchEvent(), which means we intercept the motion event.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEZHS0baGXmgnaWEWJjoLA.png" /><figcaption>The draft of the UI</figcaption></figure><p>I printed some logs in onInterceptTouchEvent() and the onTouchEvent() method of SwipeRecyclerView. And I found something strange. When the ACTION_DOWN event is passed to the onInterceptEvent(), the method doesn&#39;t return true, but remain motion events are all passed to the onTouchEvent() method. As the strategy of event-dispatching in Android, the onTouchEvent() won&#39;t be invoked unless the onInterceptTouchEvent() returns true. Maybe I didn&#39;t know the side case of the event dispatching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWr0R3viPwm6mUsja5bPMQ.png" /><figcaption>The log in the SwipeRecyclerView</figcaption></figure><h3>2 The strategy of event dispatching</h3><h4><strong>How does the View and ViewGroup handle touch events?</strong></h4><p>We know that the View is the parent of ViewGroup. The difference between them is that ViewGroup can hold some child views (When I mention child view, most of the time it means View and ViewGroup). Therefore, there must be differences when they deal with touch events.</p><p><strong>ViewGroup</strong></p><ul><li>dispatchTouchEvent() -- Dispatching touch events.</li><li>onInterceptTouchEvent() -- Deciding whether to intercept the touch event or not.</li><li>onTouchEvent() -- If decide to intercept, consume the touch event in this function. (ViewGroup does not override this function. It is provided by the View)</li></ul><p><strong>View</strong></p><ul><li>dispatchTouchEvent() -- Dispatching touch events.</li><li>onTouchEvent() -- If decide to intercept, consume the touch event in this function.</li></ul><p>View doesn&#39;t have the onInterceptTouchEvent() method. <strong>WHY?</strong> It&#39;s easy to understand. Thinking of the view hierarchy in a binary tree. The View cannot hold any child view. It must be the leaves node in the whole view tree, which means there is no need for the View to pass the touch event to the child view.</p><h4>How does the whole view tree handle touch events?</h4><p>The order of dispatching the touch events<strong>: Activity → Window → DecorView → child view → …</strong></p><p>Thinking about the question I asked at the beginning. When the touch event arrives at the SwipeRecyclerView, it&#39;ll ask SwipeRecyclerView to intercept in the onInterceptTouchEvent() method. If SwipeRecyclerView says no, the event will be passed to the child view (the FrameLayout).</p><p>We didn’t customize the FrameLayout. It won&#39;t intercept the touch events and consume them. The FrameLayout will ask its child view who is willing to take over the touch event. The key point is that FrameLayout won&#39;t ask every child view it holds. It depends on the position where the touch event occurs. The ViewGroup only asks those child views that contain the position of the touch event occurring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1JrDg-aTeJhgGQtGaqkdQ.png" /></figure><h3>3 The source code of event dispatching</h3><p>What I said above is conclusive, and I don’t give any evidence to prove it, which is what I’m going to do in the next step, I have to make it clear through the source code of ViewGroup.</p><p>Here is part of the source code of ViewGroup. I&#39;ll explain everything in the comment step by step.</p><pre>/**<br>* The Part of {ViewGroup} source code.<br>* SDK 33<br>*/<br><br>@Override<br>public boolean dispatchTouchEvent(MotionEvent ev) {<br><br>    // ...<br><br>    boolean handled = false;<br>    if (onFilterTouchEventForSecurity(ev)) {<br>        // Check for interception.<br>        final boolean intercepted;<br>        // 1. When the ACTION_DOWN comes and the <br>        //    child view allows us to intercept it, <br>        //    we&#39;ll invoke the onInterceptTouchEvent() method.<br>        // 2. If the event is not an ACTION_DOWN and <br>        //    mFirstTouchTarget is null, the view intercepts events by default.<br>        // 3. WHAT is the mFirstTouchTarget？<br>        // 4. WHEN does the mFirstTouchTarget to be assigned a value？<br>        if (actionMasked == MotionEvent.ACTION_DOWN<br>                || mFirstTouchTarget != null) {<br>            final boolean disallowIntercept = (mGroupFlags &amp; FLAG_DISALLOW_INTERCEPT) != 0;<br>            if (!disallowIntercept) {<br>                intercepted = onInterceptTouchEvent(ev);<br>                ev.setAction(action); // restore action in case it was changed<br>            } else {<br>                intercepted = false;<br>            }<br>        } else {<br>            // There are no touch targets and this action is not an initial down<br>            // so this view group continues to intercept touches.<br>            intercepted = true;<br>        }<br>    }<br><br>    // ...<br><br>    final int childrenCount = mChildrenCount;<br>    if (newTouchTarget == null &amp;&amp; childrenCount != 0) {<br>        // Find a child that can receive the event.<br>        // Scan children from front to back.<br>        final View[] children = mChildren;<br>        for (int i = childrenCount - 1; i &gt;= 0; i--) {<br>            // ...<br><br>            // whether the events happen in the area of child view?<br>            // If not, no need for dispatching the event to the child view.<br>            if (!child.canReceivePointerEvents()<br>                    || !isTransformedTouchPointInView(x, y, child, null)) {<br>                ev.setTargetAccessibilityFocus(false);<br>                continue;<br>            }<br><br>            // ...<br><br>            // If child view has been added in mFirstTouchTarget,<br>            // no need to execute the remaining logic.<br>            newTouchTarget = getTouchTarget(child);<br>            if (newTouchTarget != null) {<br>                // Child is already receiving touch within its bounds.<br>                // Give it the new pointer in addition to the ones it is handling.<br>                newTouchTarget.pointerIdBits |= idBitsToAssign;<br>                break;<br>            }<br><br>            // 1. If child is not null, <br>            //    invoke dispatchTouchEvent() of child view.<br>            // 2. Only the child view consumes the event, the <br>            //    ispatchTransformedTouchEvent() returns true. <br>            //    Then the child view will be added in mFirstTouchTarget.<br>            // 3. The mFirstTouchTarget is a linked list that <br>            //    stores child views that can consume touch events.<br>            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {<br>                // Child wants to receive touch within its bounds.<br>                mLastTouchDownTime = ev.getDownTime();<br>                if (preorderedList != null) {<br>                    // childIndex points into presorted list, find original index<br>                    for (int j = 0; j &lt; childrenCount; j++) {<br>                        if (children[childIndex] == mChildren[j]) {<br>                            mLastTouchDownIndex = j;<br>                            break;<br>                        }<br>                    }<br>                } else {<br>                    mLastTouchDownIndex = childIndex;<br>                }<br>                mLastTouchDownX = ev.getX();<br>                mLastTouchDownY = ev.getY();<br>                // The exact place where adding child views in mFirstTouchTarget.<br>                newTouchTarget = addTouchTarget(child, idBitsToAssign);<br>                alreadyDispatchedToNewTouchTarget = true;<br>                break;<br>            }<br>        }<br>    }<br><br>    // ...<br><br>    // Dispatch to touch targets.<br>    if (mFirstTouchTarget == null) {<br>        // No touch targets so treat this as an ordinary view.<br>        // It will invoke super.dispatchTouchEvent() method.<br>        // Finally invoke onTouchEvent() method of the current view.<br>        handled = dispatchTransformedTouchEvent(ev, canceled, null,<br>                TouchTarget.ALL_POINTER_IDS);<br>    } else {<br>        // Dispatch to touch targets, excluding the new touch target if we already<br>        // dispatched to it.  Cancel touch targets if necessary.<br>        TouchTarget predecessor = null;<br>        TouchTarget target = mFirstTouchTarget;<br>        while (target != null) {<br>            final TouchTarget next = target.next;<br>            if (alreadyDispatchedToNewTouchTarget &amp;&amp; target == newTouchTarget) {<br>                handled = true;<br>            } else {<br>                final boolean cancelChild = resetCancelNextUpFlag(target.child)<br>                        || intercepted;<br>                // Iterating mFirstTouchTarget. Passing the events to the child views.<br>                if (dispatchTransformedTouchEvent(ev, cancelChild,<br>                        target.child, target.pointerIdBits)) {<br>                    handled = true;<br>                }<br>                if (cancelChild) {<br>                    if (predecessor == null) {<br>                        mFirstTouchTarget = next;<br>                    } else {<br>                        predecessor.next = next;<br>                    }<br>                    target.recycle();<br>                    target = next;<br>                    continue;<br>                }<br>            }<br>            predecessor = target;<br>            target = next;<br>        }<br>    }<br>    // ...<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01a3b2a966b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Note: The activity lifecycle — the lifecycle callbacks]]></title>
            <link>https://medium.com/@yozyyyqls/android-note-the-activity-lifecycle-the-lifecycle-callbacks-b6708d8e4224?source=rss-2c847649d308------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6708d8e4224</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-lifecycle]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Chiu]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 09:51:16 GMT</pubDate>
            <atom:updated>2024-04-12T11:52:06.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Note: The activity lifecycle — the lifecycle callbacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ML05zxbxoOTmcRAd" /><figcaption>Photo by <a href="https://unsplash.com/@honza_kahanek?utm_source=medium&amp;utm_medium=referral">Jan Kahánek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This blog is only for personal study, and it keeps updating.</p><p><strong>Preface</strong></p><p>I’m developing a home call application on the inSight device. When I’m on the calling page, I hope the calling page shuts down when it’s covered by another page. So I consider implementing it by writing the shutdown logic in the activity lifecycle callback method. But I’m not sure that should I choose the onPause() method or the onStop() method. So I read the Android developer guide.</p><p><strong>When does the system call onPause() and onStop()?</strong></p><pre>onPause(): When the activity is no longer in the foreground.<br>onStop() : When the activity is no longer visible to the user.</pre><p><strong>How do we understand “foreground” and “visible”?</strong></p><p>If the activity is not in the foreground, it may still be visible to the user. But if the activity is not visible, it must be not in the foreground.</p><p>The scenario that the activity is not in the foreground:</p><ul><li>In the multi-window mode, you click another window. Only one window is focused at any time.</li><li>You open a semi-transparent activity.</li><li>A dialog pops up but does not completely cover the activity.</li></ul><p>The scenario that the activity is not visible to the user:</p><ul><li>You open a newly launched activity.</li></ul><p><strong>What kind of thing we should do in the onPause()?</strong></p><p>1)Release the system resources that the user does not need them. For example:</p><ul><li>The listener for the network.</li><li>The GPS service.</li><li>The camera/video service.</li></ul><blockquote>The onPause() method is very brief and don’t have enough time to perform save operations. For this reason, do not perform database operations and meke network calls.</blockquote><p><strong>What kind of thing we should do in the onStop()?</strong></p><p>1)Release the resources that are not needed while the app is not visible to the user. For example:</p><ul><li>The animation.</li><li>The image resources. (To avoid the OOM in the case the user opens a deep stack of activities. <a href="https://github.com/bumptech/glide/issues/942">Here</a> is an example of Glide)</li></ul><p>2)Save the information to the database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6708d8e4224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ADB Commands — Part 1: dumpsys]]></title>
            <link>https://medium.com/@yozyyyqls/adb-commands-part-1-dumpsys-f3396f550ff0?source=rss-2c847649d308------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3396f550ff0</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[adb-commands]]></category>
            <dc:creator><![CDATA[Chiu]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 14:44:56 GMT</pubDate>
            <atom:updated>2024-04-12T12:01:12.037Z</atom:updated>
            <content:encoded><![CDATA[<h3>ADB Commands — Part 1: dumpsys</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNO64D3KFY6831E6" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>This blog keeps updating.</em></p><p><strong>#1 Get the foreground Activity.</strong></p><pre># Method 1<br>&gt; adb shell dumpsys activity activities | grep mResumedActivity</pre><pre># Method 2<br>&gt; adb shell dumpsys window | grep mCurrentFocus</pre><p><strong>#2 Get all task stacks.</strong></p><pre>&gt; adb shell dumpsys activity activities<br><br># The ouput is tons of strings. I won&#39;t show them here.</pre><p>To simplify the output, we can type the following command to get the number of tasks.</p><pre>&gt; adb shell dumpsys activity activities | grep &quot;Stack #&quot;<br><br>  Stack #4: type=standard mode=fullscreen<br>  Stack #0: type=home mode=fullscreen<br>  Stack #3: type=standard mode=fullscreen<br><br># You can see there is three tasks.</pre><p>Then we look back to the command.</p><pre>&gt; adb shell dumpsys activity activities<br># or you can use:<br>&gt; adb shell dumpsys activity activities<br><br># Attention: This is a part of the output. Not the full content.<br><br>  Stack #4: type=standard mode=fullscreen<br>  isSleeping=false<br>  mBounds=Rect(0, 0 - 0, 0)<br>    Task id #3<br>    mBounds=Rect(0, 0 - 0, 0)<br>    mMinWidth=-1<br>    mMinHeight=-1<br>    mLastNonFullscreenBounds=null<br>    * TaskRecord{65afd1 #3 A=10040:com.duolingo U=0 StackId=4 sz=2}<br>      userId=0 effectiveUid=u0a40 mCallingUid=u0a101 mUserSetupComplete=true mCallingPackage=com.huawei.android.launcher<br>      affinity=10040:com.duolingo<br>      intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10300000 cmp=com.duolingo/.app.LoginActivity}<br>      origActivity=com.duolingo/.app.LoginActivity<br>      mActivityComponent=com.duolingo/.splash.LaunchActivity<br>      autoRemoveRecents=false isPersistable=true numFullscreen=2 activityType=1<br>      rootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE<br>      Activities=[ActivityRecord{393687 u0 com.duolingo/.app.LoginActivity t3}, ActivityRecord{393c87 u0 com.duolingo/.signuplogin.SignupActivity t3}]<br>      askedCompatMode=false inRecents=true isAvailable=true<br>      mRootProcess=ProcessRecord{396cb1 9505:com.duolingo/u0a40}<br>      stackId=4<br>      hasBeenVisible=true mResizeMode=RESIZE_MODE_UNRESIZEABLE mSupportsPictureInPicture=false isResizeable=false lastActiveTime=3827733 (inactive for 1s)<br>      * Hist #1: ActivityRecord{393c87 u0 com.duolingo/.signuplogin.SignupActivity t3}<br>          packageName=com.duolingo processName=com.duolingo<br>          launchedFromUid=10040 launchedFromPackage=com.duolingo userId=0<br>          app=ProcessRecord{396cb1 9505:com.duolingo/u0a40}<br>          Intent { cmp=com.duolingo/.signuplogin.SignupActivity (has extras) }<br>          frontOfTask=false task=TaskRecord{65afd1 #3 A=10040:com.duolingo U=0 StackId=4 sz=2}<br>          taskAffinity=10040:com.duolingo<br>          mActivityComponent=com.duolingo/.signuplogin.SignupActivity<br>          ... ...<br>      * Hist #0: ActivityRecord{393687 u0 com.duolingo/.app.LoginActivity t3}<br>          packageName=com.duolingo processName=com.duolingo<br>          launchedFromUid=10101 launchedFromPackage=com.huawei.android.launcher userId=0<br>          app=ProcessRecord{396cb1 9505:com.duolingo/u0a40}<br>          Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10300000 cmp=com.duolingo/.app.LoginActivity (has extras) }<br>          frontOfTask=true task=TaskRecord{65afd1 #3 A=10040:com.duolingo U=0 StackId=4 sz=2}<br>          taskAffinity=10040:com.duolingo<br>          mActivityComponent=com.duolingo/.splash.LaunchActivity<br>          ... ...<br><br>    # 👇👇👇 We can see all instances of Activity in the task.<br>    Running activities (most recent first):<br>      TaskRecord{65afd1 #3 A=10040:com.duolingo U=0 StackId=4 sz=2}<br>        Run #1: ActivityRecord{393c87 u0 com.duolingo/.signuplogin.SignupActivity t3}<br>        Run #0: ActivityRecord{393687 u0 com.duolingo/.app.LoginActivity t3}<br><br>    mResumedActivity: ActivityRecord{393c87 u0 com.duolingo/.signuplogin.SignupActivity t3}<br>    mLastPausedActivity: ActivityRecord{393687 u0 com.duolingo/.app.LoginActivity t3}</pre><p><strong>#3 Get the lifecycle state of the activity.</strong></p><p>I know we can print the log in each lifecycle callback. Sometimes you don’t print the log in the lifecycle callback, but you need to know what state currently the activity is.</p><pre>&gt; adb shell dumpsys activity a<br><br># Attention: This is a part of the output. Not the full content.<br>... ...<br>* Hist #0: ActivityRecord{a48805f u0 com.knowin.guard/.dnake.HomeCallActivity t122}<br>          packageName=com.knowin.guard processName=com.knowin.guard<br>          launchedFromUid=1000 launchedFromPackage=com.knowin.guard userId=0<br>          app=ProcessRecord{63be592 1111:com.knowin.guard/1000}<br>          Intent { act=com.knowin.guard.home.call flg=0x10800000 cmp=com.knowin.guard/.dnake.HomeCallActivity (has extras) }<br>          frontOfTask=true task=TaskRecord{1cc036c #122 A=com.knowin.guard U=0 StackId=22 sz=1}<br>          taskAffinity=com.knowin.guard<br>          realActivity=com.knowin.guard/.dnake.HomeCallActivity<br>          baseDir=/system/app/InsightGuard/InsightGuard.apk<br>          dataDir=/data/user/0/com.knowin.guard<br>          stateNotNeeded=false componentSpecified=false mActivityType=standard<br>          compat={332dpi always-compat} labelRes=0x7f100024 icon=0x7f0d0017 theme=0x7f11000a<br>          mLastReportedConfigurations:<br>           mGlobalConfig={1.0 ?mcc?mnc [zh_CN] ldltr sw231dp w231dp h373dp 332dpi smll port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 0, 0) mAppBounds=Rect(0, 0 - 480, 854) mWindowingMode=fullscreen mActivityType=undefined} s.5}<br>           mOverrideConfig={1.0 ?mcc?mnc [zh_CN] ldltr sw231dp w231dp h373dp 332dpi smll port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 480, 854) mAppBounds=Rect(0, 0 - 480, 854) mWindowingMode=fullscreen mActivityType=standard} s.5}<br>          CurrentConfiguration={1.0 ?mcc?mnc [zh_CN] ldltr sw231dp w231dp h373dp 332dpi smll port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 480, 854) mAppBounds=Rect(0, 0 - 480, 854) mWindowingMode=fullscreen mActivityType=standard} s.5}<br>          taskDescription: label=&quot;null&quot; icon=null iconResource=0 iconFilename=null primaryColor=ff1e1f20<br>           backgroundColor=fffafafa<br>           statusBarColor=ff1e1f20<br>           navigationBarColor=ff000000<br>          launchFailed=false launchCount=1 lastLaunchTime=-7s590ms<br>          haveState=false icicle=null<br>          # 👇👇👇 Find the &quot;state&quot;<br>          state=RESUMED stopped=false delayedResume=false finishing=false<br>          keysPaused=false inHistory=true visible=true sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_SHOWN<br>          fullscreen=true noDisplay=false immersive=false launchMode=0<br>          frozenBeforeDestroy=false forceNewConfig=false<br>          mActivityType=standard<br>          waitingVisible=false nowVisible=true lastVisibleTime=-6s923ms<br>          resizeMode=RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION<br>          mLastReportedMultiWindowMode=false mLastReportedPictureInPictureMode=false<br>... ...</pre><p><strong>References may help</strong></p><p>#1: <a href="https://weiwangqiang.github.io/2020/03/16/dumpsys-debug-detail/">https://weiwangqiang.github.io/2020/03/16/dumpsys-debug-detail/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3396f550ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Talking about ViewPager2: The Lifecycle of Fragments]]></title>
            <link>https://medium.com/@yozyyyqls/talking-about-viewpager2-the-lifecycle-of-fragments-759714503233?source=rss-2c847649d308------2</link>
            <guid isPermaLink="false">https://medium.com/p/759714503233</guid>
            <category><![CDATA[fragment-lifecycle]]></category>
            <category><![CDATA[android-fragment]]></category>
            <category><![CDATA[android-viewpager]]></category>
            <category><![CDATA[viewpager2]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chiu]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 14:51:01 GMT</pubDate>
            <atom:updated>2024-03-22T14:51:01.854Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*90ZAnu57gxHNs6zD" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Emile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog, We write an Activity, that has one ViewPager2 UI component holding some Fragments, to see the Fragments’ life cycle changing and how the ViewPager Adapter manages the list of Fragment instances at the default mode. <strong>The default mode means we don’t use setOffscreenPageLimit(<em>int </em>limit) to set up the number of pages that should be retained on the side of the currently visible page.</strong></p><p>The following graphic shows the UI hierarchy of the CollectionActivity. The ViewPager2 holds several Fragments. When we are swiping between these Fragments, what happens in their life cycle?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Dh5VOaqSfrHK34bG-AuxWw.png" /><figcaption>The UI hierarchy of the <em>CollectionActivity.</em></figcaption></figure><p>We set five Fragments in ViewPager2. Now we open our Application to see what’s going on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*NYlnF0cCsvcgMTWFVkGdlA.png" /><figcaption>The CollectionActivity.</figcaption></figure><h3>Case 1: The initialization of Fragment0</h3><p>As you can see in the Logcat, when we open the CollectionActivity, the ViewPager Adapter will instantiate the first Fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzNM-eudmA6few0aKTKCBg.png" /><figcaption>The Logcat printing log of Fragment.</figcaption></figure><h3>Case 2: From Fragment0 sliding to Fragment1</h3><p>When we’re sliding to Fragment One from Fragment Zero, the Adapter initializes the instance of Fragment One and its life cycle goes to onStart(). As the Fragment Zero didn’t show on the screen, it goes to onPause(). The Fragment One goes to onResume(). It’s kind of like the process of switching between two Activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWEYdhRch82AD8HXWQjaVg.png" /><figcaption>The Logcat content when we slide to the second Fragment.</figcaption></figure><h3>Case 3: From Fragment1 sliding to Fragment0</h3><p>The instance of Fragment Zero has been initialized before. So when we slide back to Fragment Zero, it won’t be created again. This is the cache strategy of ViewPager2 (We won’t talk about that here).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrbhFUQ4acJwg1vM53Jfjg.png" /><figcaption>The Logcat content when we slide to the first Fragment from the second one.</figcaption></figure><h3>Case 4: From Fragment0 jumping to Fragment4</h3><p>Fragment Two, Three, and Four will be created and go to the onStart(). They won’t show on the screen so there’s no need to call the onResume() callback method.</p><p>The size of the Fragments cache list, held by the ViewPager Adapter, is limited. Once reaching out to the limited number, one instance of Fragment will be removed from the cache list (We don’t discuss which Fragment will be removed here) and go to the onDestroy() method. Such as the Fragment Zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PlIUJAO576t3bTvXYXcgQ.png" /><figcaption>The Logcat content when jumping to the fifth page from the first one.</figcaption></figure><h3>Case 5: From Fragment4 jump to Fragment0</h3><p>Although we jump to Fragment Zero from the Four, the process seems more like sliding one by one from the Four to Zero. Due to the caching strategy, the instance of Fragment Four will be destroyed. The Fragment One will be created and attached to the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxCy50lvH67Ue7kEX4ggdA.png" /><figcaption>The Logcat content when jumping to the first page from the fifth page.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759714503233" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>