<?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 York on Medium]]></title>
        <description><![CDATA[Stories by York on Medium]]></description>
        <link>https://medium.com/@kmgs4524?source=rss-6e154a228566------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gkjjKHjM2cdSFDJj.</url>
            <title>Stories by York on Medium</title>
            <link>https://medium.com/@kmgs4524?source=rss-6e154a228566------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 19:30:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kmgs4524/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[View 原理 — MeasureSpec & LayoutParams]]></title>
            <link>https://kmgs4524.medium.com/view-%E5%8E%9F%E7%90%86-measurespec-layoutparams-fc69367c60e6?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc69367c60e6</guid>
            <category><![CDATA[measure]]></category>
            <category><![CDATA[measurespec]]></category>
            <category><![CDATA[views]]></category>
            <category><![CDATA[view-繪製]]></category>
            <category><![CDATA[layoutparams]]></category>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Wed, 18 Nov 2020 06:52:48 GMT</pubDate>
            <atom:updated>2020-11-18T06:52:48.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>View 原理 — MeasureSpec &amp; LayoutParams</h3><p>有時我們需要自己客製 UI 元件，此時就需要懂 View 的繪製原理。在這篇文章會介紹到：</p><ul><li>View 的繪製流程會經過的三個階段</li><li>layoutParams 和 MeasureSpec 在 measure 階段有什麼用處</li></ul><h3>View 是如何畫出來的？</h3><p>View 顯示在畫面上需要經過三個階段，就像一般畫畫的過程一樣，我們需要先知道要畫的元件寬高要是多少、應該畫在哪個地方，最後才畫出圖案。因此三個階段分別是：</p><p><strong>measure</strong>：測量 View 在父 View 中的寬高應該要是多少</p><p><strong>layout</strong>：決定 View 在父 View 中的位置</p><p><strong>draw</strong> ：將 View 繪製在父 View 上</p><h3>Measure 流程</h3><p>在 View 測量自己寬高時會用到父 View 的 MeasureSpec 和自己的 layoutParams 來決定寬高要多少。</p><p><strong>LayoutParams</strong></p><p>佈局參數，包含 View 的寬高，用來告訴父 View 自己該如何被測量</p><p>LayoutParams.MATCH_PARENT：父 View 多大就跟著多大（扣掉 padding）</p><p>LayoutParams.WRAP_CONTENT：大小足夠包含自己的內容（含 padding）</p><p><strong>MeasureSpec</strong></p><p>父 View 測量子 View 的規則，分三種模式：</p><p>UNSPECIFIED：父 View還沒測量出確切值之前傳的模式，沒有太大用意</p><p>AT_MOST：強制最大只能是特定大小，子 View 的大小不能超過這個大小</p><p>EXACTLY：強制子 View 必須要用傳來的確切大小，保證子View內的View必須在這個大小內</p><p>父 View 在 measure() 傳來的 widthMeasureSpec, heightMeasureSpec 是個 int 值，包含兩個訊息 SpecMode 和 SpecSize，SpecMode 是 UNSPECIFIED, AT_MOST, EXACTLY 三種模式其中一種，SpecSize 則是父 View 限制子 View 的大小，兩者可以藉由 MeasureSpec.getMode(measureSpec), MeasureSpec.getSize(measureSpec) 解析出來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*6SzZ52CuI_PND2Yli1Wh7w.png" /></figure><h4>View 的 measure 過程</h4><p>View 在 onMeasure() 藉由父 View 傳來的 MeasureSpec 和自己的 LayoutParams 決定測量出來的大小，當 measure() 回傳後 measuredWidth、measuredHeight 的值就會被設置了，父 View 會執行子 View 的 measure() 不只一次，父 View 為了找出子 View 的大小會先執行一次 measure() 帶 UNSPECIFIED，當發現大小超過父 View 的限制時再執行一次 measure() 帶入 AT_MOST 或 EXACTLY。繼承 View 或 ViewGroup 的類別必須覆寫 onMeasure，在這邊決定 measuredWidth、measuredHeight。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbbf7fd1d9ec586fb85513b72b5fdc67/href">https://medium.com/media/fbbf7fd1d9ec586fb85513b72b5fdc67/href</a></iframe><p><strong>那麼父 View 的 MeasureSpec 又是指什麼呢？其實就是 ViewGroup 的 MeasureSpec</strong></p><h4>ViewGroup 的 measure 過程</h4><p>View 階層的根 View 是 DecorView，啟動 Activity 時會將 DecorView 加到 Window 同時建立 RootViewImple，並將 DecorView 設置到 RootViewImpl。View 階層的繪製過程就是從 RootViewImpl 開始的，在 performTraversals() 執行了 performMeasure()、 performLayout()、performDraw()，這三個方法又分別執行了 View 的 measure()、 layout()、draw()。</p><p>measure() 在 View 是 final 無法被覆寫，因此實作 ViewGroup 的類別實作測量子 View 寬高的邏輯是在 onMeasure() 實現，例如 LinearLayout、RelativeLayout 等等，他們的 onMeasure 實作都不一樣。</p><p>以 LinearLayout 為例：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f06386d35a6192db91fa2272e5e3a163/href">https://medium.com/media/f06386d35a6192db91fa2272e5e3a163/href</a></iframe><p>關鍵在 getChildMeasureSpec 這個方法，這邊依據父 View 的 MeasureSpec 和子 View 的 LayoutParams 決定子 View 的 MeasureSpec</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/415912e2fc5e7ae23449060d236d234f/href">https://medium.com/media/415912e2fc5e7ae23449060d236d234f/href</a></iframe><p>既然 View 的寬高是由父 View 的 MeasureSpec 和自己的 LayoutParams 決定的，那麼最初始的 DecorView 又是怎麼決定大小的呢？從 ViewRootImpl 的 getRootMeasureSpec() 可以看到 MeasureSpec 是以 ＷindowManager.LayoutParams 決定，WindowManager.LayoutParams 的初始值是 LayoutParams.MATCH_PARENT</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/547bae537eca96a1523e4356419b3e3a/href">https://medium.com/media/547bae537eca96a1523e4356419b3e3a/href</a></iframe><h4>總結</h4><p>研究到這邊，對於 measure 階段如何測量 View 寬高有基本的理解了，如果自製的 View 包含了某個 TextView 時，想要將 TextView 的位置置中的話，就該用 measured width 來調整，因為在 onLayout 時整個 View 已經測量過寬高了。</p><p>以上是自己研究 View 如何實作 measure 所做的整理 希望對於想了解 View 寬高是如何決定的人能夠一些幫助，或者文章中有任何錯誤的地方也歡迎指正~</p><p>參考連結</p><ul><li><a href="https://developer.android.com/guide/topics/ui/how-android-draws">How Android Draws Views | Android Developers</a></li><li><a href="https://juejin.im/post/6844903828584660999#heading-6">View的绘制-measure流程详解</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc69367c60e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 記憶體管理 — Part 1 (Memory Leak)]]></title>
            <link>https://kmgs4524.medium.com/android-%E8%A8%98%E6%86%B6%E9%AB%94%E7%AE%A1%E7%90%86-part-1-memory-leak-89e2c1b3a918?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/89e2c1b3a918</guid>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 19:41:28 GMT</pubDate>
            <atom:updated>2019-01-25T19:47:06.784Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android 記憶體管理 — Part 1 (Memory Leak)</h3><h3>何謂 Memory Leak？</h3><p>記憶體洩漏 ( Memory Leak ) 可說是每個 Android 開發者都很常遇到的問題，顧名思義就是指因為疏誤或錯誤導致程式無法釋放不再使用的記憶體。更明確地來說，是指應用程式所分配到的某段記憶體空間在釋放前就失去了控制權，導致該段記憶體無法回收。而在探討可能發生 Memory Leak 的幾種情況前，我們須先了解一下 ART 的 Garbage Collection 機制。</p><h4>Garbage Collection</h4><p>所謂的 Garbage Collection，是指在大部分的虛擬機器 (不論是 ART 或 Dalvik) 中，會由一種稱作可達性分析的演算法追蹤記憶體的配置情況，用來決定哪些是未來可能不再被使用的對象 (物件)，回收對象所占用的資源。原理則是：有幾個對象作為 root 節點，從這些起始點開始向下搜尋，搜尋的路徑就是各個對象的參照鍊。</p><p>例如從下圖來看：從 GC Roots 開始，每個 root 參照到某些對象，而那些對象也同樣參照了其他的對象。由此便能得知目前正在使用及可能不再被使用的物件，進而決定要回收哪些物件所占用的記憶體資源。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*mV4IRA-dmpGdLTBj.png" /></figure><p>了解 GC ( Garbage Collection ) 後，我們便能得知 Android 中的 Memory Leak 就是指：</p><p><em>對象雖然已不再被使用，卻因為一直被 roots 所參照到，導致無法回收對象占用的記憶體空間，因而稱作洩漏 ( Leak )。</em></p><h3>何時會發生 Memory Leak？</h3><p>再來我們看看以下幾種常見記憶體洩漏的情景：</p><p><strong>static</strong></p><p>當一個變數指定為 static (靜態) 時，代表它從程式開始執行時便產生了，而且它的壽命直到程式結束時才終止。因此當某個對象被靜態變數參照時是無法回收的。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61ef0e82dc7b049e0a82b59a7c3593cc/href">https://medium.com/media/61ef0e82dc7b049e0a82b59a7c3593cc/href</a></iframe><p><strong>inner class</strong></p><p>內部類別的實例會參照到外部類別的實例，因此當內部類別的實例一直存活時，外部類別的實例也就永遠不會被回收。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61ef0e82dc7b049e0a82b59a7c3593cc/href">https://medium.com/media/61ef0e82dc7b049e0a82b59a7c3593cc/href</a></iframe><h3>該如何檢查 Memory Leak？</h3><p>個人認為目前最容易檢查記憶體洩漏的工具應該是 LeakCanary。使用方法非常簡單，有興趣的人可以自行去官方的 Github 看看如何使用。</p><p>這邊直接我們用靜態變數參照到本應回收的物件來示範使用 LeakCanary 的結果。</p><p>首先建立兩個 Activity，分別是 MainActivity 和 LeakActivity，MainActivity 有個 Button，按下去後會進入 LeakActivity 的畫面。而在建立 LeakActivity 時，指定一個靜態變數的對象為 LeakActivity 本身，再來只要按下手機的返回鍵後，就會照預期的發生記憶體洩漏了。</p><p><strong>LeakActivity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*jAbNEzGhJWIPJDEBzo4i4w.png" /></figure><p>發生洩漏時， LeakCanary 會發出洩漏的通知，另外我們可以開啟 LeakCanary 的 APP 來看看洩漏的詳細資訊：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ApEph05tUDmsCrl6JCjDeQ.png" /></figure><h3>總結</h3><p>避免 Memory Leak 的方法便是平常開發時，盡量避免用靜態變數存 Activity, View 等元件，另外盡量少用匿名類別變數來實作非同步工作或是耗時程序。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89e2c1b3a918" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[探討 Android Threading Performance — Part 1 ( Thread 執行緒的概念)]]></title>
            <link>https://kmgs4524.medium.com/%E6%8E%A2%E8%A8%8E-android-threading-performance-1-9d1f665e58df?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d1f665e58df</guid>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 16:18:59 GMT</pubDate>
            <atom:updated>2018-07-07T08:18:57.270Z</atom:updated>
            <content:encoded><![CDATA[<h3>Thread 究竟負責做什麼 ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*9D0hbKZ_LfK_BmiMhrTRng.png" /></figure><p>從上圖可看出，Thread 從頭到尾只做三件事，開始、做工作、結束，更詳細一點來說，Thread 開始時會有 loop 運行在 Thread 上面，loop 能從 WorkQueue 中將一些工作拉進來執行，另一方面也需要從其他的 Thread 不斷推進工作到 WorkQueue，如此便能保持 Thread 持續存活。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*lSgOySrJ1uWF5S0IdmuX8g.png" /><figcaption>Thread 的運作原理</figcaption></figure><p>Android 提供一些 class 來幫助我們處理這些細節，例如 <strong>Looper </strong>(又稱作 <strong>Event Loop</strong>)，會保持 Thread 活著並且從 MessageQueue 提取工作到 Thread 上執行。另外 Looper 的特性是只能從 queue 的尾端推進工作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*4ptkrUTJ6nnIKUIAXm1d1A.png" /><figcaption>Looper 運作原理</figcaption></figure><p>除了 Looper 以外，還有個類似的 Handler class。它與 Looper 不同之處在於 能從 queue 的頭、尾端推進工作，另外還能設定延遲時間來決定工作要隔多久才被處理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*CZ8x7yzcUyLptNqbg0ldhQ.png" /></figure><p>前面所講到的工作被定義成幾種單位：Intent, Runnable, Message。使用哪種單位取決於由誰宣告及使用( Looper or Handler )。</p><p>在本文最後會簡單介紹一些將<strong>工作排程</strong>和<strong>建立 Thread</strong> 結合在一起的幾種 class，但在介紹使用 HandlerThread 之前我們先來看看 APP 的 Main Thread。</p><h3>常聽到的 Main Thread 都做了什麼事呢？</h3><p>當使用者啟動 APP 時，Android 會建立自己的 Linux process ，伴隨著這個 process，系統建立一個專門執行 APP 的 Thread，這個 Thread 就是我們俗稱的 Main Thread，它本身就是一個 Handler Thread。Main Thread 處理所有遍及整個 APP 的事件，例如和<strong>生命週期</strong>相關的 callback: onCreate(), onStart(), onDestory()，或是<strong>輸入事件</strong>的 callback ，甚至是從其他 APP 傳來的事件等等。</p><p>從下圖可看出我們想要運行的程式碼都必須推進 Work Queue，代表 Main Thread 要處理非常多的工作，這也是為何我們必須將要花較長時間處理的工作交由其他的 Thread 來處理，以免這些耗時工作妨礙繪製 UI ( Rendering ) 的工作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*9vEwIUltz7UNKP5mbkLwPw.png" /></figure><h3>另開 Thread 執行耗時工作的幾種方案</h3><p>在知道要避免在 Main Thread 執行耗時工作之後，我們必須使用先前提到能夠將<strong>工作排程</strong>和<strong>建立 Thread</strong> 結合在一起的 class。有以下幾種選擇能夠使用：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*VqPjHYmhcvBhBgLqwP5bzA.png" /></figure><p>這邊我只針對使用過的 AsyncTask, HandlerThread, IntentService 做介紹。首先 AsyncTask 特色在於能將背景工作及更新 UI 的程式碼區分開來，而 HandlerThread 則是能夠直接建立一個新的 Thread 上執行的 Handler。 IntentService 則是一種在新的 Thread 上執行的 Service，且當工作結束後會自行關閉。</p><p>並沒有能夠在任何情況下，都適用的類別能用，在哪種情境要使用相對適合的類別也需要一點經驗，今後有機會在針對這三種開啟新 Thread ，執行耗時工作的類別做介紹。</p><p>參考影片連結： <a href="https://www.youtube.com/watch?v=qk5F6Bxqhr4&amp;index=1&amp;list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE">https://www.youtube.com/watch?v=qk5F6Bxqhr4&amp;index=1&amp;list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d1f665e58df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[使用 SimpleDateFormat, Calendar — 計算兩個日期間的天數]]></title>
            <link>https://kmgs4524.medium.com/%E4%BD%BF%E7%94%A8-simpledateformat-calendar-%E8%A8%88%E7%AE%97%E5%85%A9%E5%80%8B%E6%97%A5%E6%9C%9F%E9%96%93%E7%9A%84%E5%A4%A9%E6%95%B8-a00b883ce28a?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00b883ce28a</guid>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Mon, 02 Jul 2018 14:53:22 GMT</pubDate>
            <atom:updated>2018-07-02T14:53:22.401Z</atom:updated>
            <content:encoded><![CDATA[<p>有時候我們從後端得到日期的字串後，需要計算不同日期之間的天數，這種時候就要使用 SimpleDateFormat 搭配 Gson 的 JsonDeserializer 將字串轉成 Date object，再使用這個物件做想要的事，譬如計算兩個特定日期間的天數之類的。轉換的概念與過程非常簡單，我們直接開始吧！</p><p>首先我們需要先了解一下 SimpleDateFormat ，這個類別能專門用來產生特定格式的日期。特別需要注意的地方在於傳入 SimpleDateFormat 建構子的字串大小寫格式是固定的，依照年、月、日、時、分、秒 來建立預期格式的字串，譬如：</p><pre>yyyy-MM-dd HH:mm:ss</pre><p>另外傳入的字串不能有多餘的部分，例如我只要年月日的話，格式便為 <strong>yyyy-MM-dd</strong>，傳入的字串便要是 <strong>2018–06–09</strong>，不能有<strong>時</strong>跟<strong>分</strong>。</p><p>假設有一個情境是要計算今天距離某個活動的日期還有多少天，那我們可以建立一個 CalculatePeriod class 專門來做這件事。藉由 getPeriodToDate(date, time) 能得到從今日起到某一天之間相隔的天數。假設 date 要傳入的字串為活動當天的日期 <strong>2018/07/04，</strong>time 的字串格式為 活動當天的時間 <strong>20:30 </strong>，我們要將兩個字串合再一起並傳入自己建立的 DateDeserizlizer class，由這個類別負責將傳入的日期時間字串轉換成代表特定日期的 Date object。再來呼叫 Calendar.getInstance() 建立 Calendar object ，使用 calendar.time 取得目前時間的 Date object。如此得到活動當天即今日的兩個物件之後，使用 Date.getTIme() 取得從 1970 年 1月 1 日開始算起的總毫秒數，將兩個日期的毫秒數相減再換算成天數就完成了！</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3296732ec72b006b5c9c7794eba65a25/href">https://medium.com/media/3296732ec72b006b5c9c7794eba65a25/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91847c6d87cc8de810fc6848c48cab5e/href">https://medium.com/media/91847c6d87cc8de810fc6848c48cab5e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00b883ce28a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[何謂測試？在Android上該如何實作？- Part 1 (單元測試)]]></title>
            <link>https://kmgs4524.medium.com/%E4%BD%95%E8%AC%82%E6%B8%AC%E8%A9%A6-%E5%9C%A8android%E4%B8%8A%E8%A9%B2%E5%A6%82%E4%BD%95%E5%AF%A6%E4%BD%9C-1-19defb91454a?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/19defb91454a</guid>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Mon, 25 Jun 2018 14:25:50 GMT</pubDate>
            <atom:updated>2018-07-03T16:20:35.577Z</atom:updated>
            <content:encoded><![CDATA[<p>測試是為了確保程式執行的結果與預期相同，開發 App 時也有許多情況下會促使開發人員先寫測試再寫產品程式碼。這邊介紹一些我學習測試的基本概念與在 Android 上的實作 Unit Test 及 UI Test 的簡單範例，希望能讓剛學習測試的人能有較明確概念。</p><h3>Test 的意義與優點</h3><p>Test (測試)是開發 App 的一部分，常常我們在開發完一個功能或流程後，需由 Test 來確認實際結果是否與預期的相同。有 Test 的好處在於能夠得到快速的回饋，以確保開發新功能時不用擔心是否會影響到原有的部分，或是回頭重構時確保程式碼的正確性，譬如我們預先想好某個 function 所要做的事並定義他的參數與回傳值，如此一來，就能針對該function寫一個 Test case ，確保在某個流程中呼叫 function 並丟入想要的參數後，他的回傳值與預期的相同。有了 Test case 後，無論之後要如何修改function內部實作的內容，我們都能藉由執行 Test case 快速得知結果是否與預期一致。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*g8F5m1AX5L_A-Dgr.png" /><figcaption>Testing Pyramid</figcaption></figure><p>如同上圖的金字塔，一個 App 應包含 Small Tests, Medium Tests, Large Tests，通常建議測試要包含70%的 small tests，20%的 medium tests，10%的 large tests 。</p><ul><li>Small tests：對應的是 Unit Tests ，可能是針對某個 function 或是 class 的test。</li><li>Medium tests：可能是 components 之間的 integration tests ，需要在emulator或是 real devices 上執行。</li><li>Latge test：藉由完成整個 UI workflow 的 UI test，確保關鍵的 user task 和預期運作的一樣。</li></ul><h3>從最基本且重要的單元測試開始！</h3><p>一個程式要最建立最多的測試就屬 unit test 了。unit tests 通常使用在最小單位的程式碼中，可能是 class, method 或 component。當要驗證某個程式碼的邏輯是否正確時，便應該使用 unit tests，因此為程式的每個重要邏輯建立unit test 便能確保可靠性。</p><p>以我之前做的找咖啡App來示範建立unit test。假設我要在MapPageFragment顯示距離最近的咖啡廳，那麼依序要做到以下兩件事：</p><ol><li>將傳進Fragment的所在位置郵遞區號的資料轉成用在查詢縣市咖啡廳API的city id。</li><li>取得某縣市的所有咖啡廳資料後再依照距離排序。</li></ol><p>為了讓每項工作的程式碼區分清楚，我以MVP架構分成 MapPageView、MapPagePresenter 和幾個 model class。由於 presenter 的每個方法都代表view 與 model 之間互動的流程，因此很適合用unit test檢查是否符合預期的結果。</p><p>依照要達成的目標，在presenter設計三個方法：</p><ul><li>getCityIdFromPostalCode()：將郵遞區號轉成city id。</li><li>getCityCafes()：利用city id 於後端API取得某縣市的所有咖啡廳。</li><li>sortSelectiveCafe()：將所有咖啡廳依照距離排序。</li></ul><p>以上方法的邏輯分別是GetCityId、GetCityCafes、SortByDistance三個model class所負責，而我可以先設計測試案例檢查他們執行的結果是否正確，因此會建立以下兩個unit tests：</p><pre><a href="http://twitter.com/Test">@Test</a><br>fun getCityIdFromPostalCode() {<br>   val getCityId = GetCityId()<br>   val postalCode = 500  // 彰化的郵遞區號<br>   Assert.assertSame(&quot;changhua&quot;, getCityId.cityId(postalCode))<br>}</pre><pre>@Test<br>fun getSelectiveCafes() {<br>   val lastLocation = Location()<br>   lastLocation.<em>latitude </em>= 23.0200729<br>   lastLocation.<em>longitude </em>= 120.2226109<br><br>   Assert.assertSame(43, getCityCafes.cafes(&quot;changhua&quot;,     lastLocation).size)</pre><pre>}</pre><pre><a href="http://twitter.com/Test">@Test</a><br>fun sortCityCafes() {<br>   val cityCafes = ArrayList&lt;Cafe&gt;()</pre><pre>   // Cafe建構子需傳入&quot;名稱&quot;、&quot;開店時間&quot;、&quot;結束時間&quot;<br>   cityCafes.add(Cafe(&quot;好想咖啡廳&quot;, &quot;10:00&quot;, &quot;20:00&quot;, 10680))<br>   cityCafes.add(Cafe(&quot;等一杯咖啡廳&quot;, &quot;11:00&quot;, &quot;21:00&quot;, 5000))<br>   cityCafes.add(Cafe(&quot;雲端咖啡廳&quot;, &quot;9:00&quot;, &quot;20:00&quot;, 25460))</pre><pre>   // 將儲存咖啡廳的 list 傳給 SortByDistance class 排序       <br>   sortByDistance.sort(selectiveCafes)<br>   <br>   // 將對或錯的排序結果傳入isDistanceIncremental<br>   val isDistanceIncremental = selectiveCafes[0].distance &lt;       selectiveCafes[1].distance &amp;&amp; selectiveCafes[1].distance &lt; selectiveCafes[2].distance<br>   <br>   Assert.assertSame(true, isDistanceIncremental)<br>}</pre><p>由以上的程式碼可以看出設計測試案例就是用 Asser.asserSame(expectValue, actualValue) 分別傳入期望的正確值和實際值來判斷執行結果是否符合預期，當然以上程式碼有簡化過，實際上會更複雜一點。但到目前為止我們已經體會到寫測試最重要的目的在於強迫自己把程式碼結構寫的更加職責分明。</p><p>以上就是寫測試最基本的且重要的單元測試，未來會陸續介紹實際寫測試時會用到的框架如 Roboletric, Mockito 等等。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19defb91454a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Location API & Google Map API]]></title>
            <link>https://kmgs4524.medium.com/location-api-google-map-api-b6ff82ba2682?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ff82ba2682</guid>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 01:51:11 GMT</pubDate>
            <atom:updated>2018-06-08T01:51:11.336Z</atom:updated>
            <content:encoded><![CDATA[<p>本章要講解如何使用Location API取得手機最後位置，用Map API加入Google地圖到App。</p><h4>要求取得手機位置的權限</h4><p>自從Android 6.0開始，若使用到App以外的資源，除了在AndroidManifest宣告權限外，還要在App執行期間跟使用者要求權限。接下來要介紹如何在run time時跳出訊息窗進一步處理取得權限與拒絕後的情況。</p><p>首先一樣要在AndroidManifest.xml中設定要取得的權限，例如App要取得手機的精準位置：</p><pre>&lt;uses-permission  android:name=”android.permission.ACCESS_FINE_LOCATION” /&gt;</pre><p>再來要跟使用者要求我們想要的權限。Android已經內建代表權限的字串變數了，因此可以直接使用，但要注意的是requestPermissions(String[], int)要求放入的是字串陣列，所以必須把代表權限的String包在陣列中。例如我們這次要取得讀取手機的位置，就直接新增一個字串陣列變數：</p><pre>val PERMISSIONS_LOCATION = arrayOf(Manifest.permmission.ACCESS_FINE_LOCATION)</pre><p>requestPermissions()的第二個參數要放入request code，因此我們也自己定義一個request code：</p><pre>val REQUEST_LOCATION = 123  // any number you want</pre><p>接著來看負責驗證權限的方法 <em>verifyStoragePermission()</em>：</p><pre>RequiresApi(Build.VERSION_CODES.O)</pre><pre>override fun verifyStoragePermission() {</pre><pre>   // Check if we have write permission</pre><pre>   val permission = ActivityCompat.checkSelfPermission(activity,Manifest.permission.WRITE_EXTERNAL_STORAGE)<br></pre><pre>   if (permission != PackageManager.PERMISSION_GRANTED) {</pre><pre>   // We don&#39;t have permission so prompt the user</pre><pre>   requestPermissions(PERMISSIONS_LOCATION,REQUEST_EXTERNAL_STORAGE)</pre><pre>   } else {</pre><pre>     // Already have permission, do actions ...</pre><pre>   }</pre><pre>}</pre><p>呼叫requestPermissions()會跳出允許存取權限的視窗。當按下允許或取消後，會再呼叫Callback method`onRequestPermissionsResult()`，並傳入requestCode、permissions、grantResults。requestCode就是呼叫requestPermissions()時傳入的第二個參數</p><pre>@RequiresApi(Build.VERSION_CODES.O)<br>override fun onRequestPermissionsResult(requestCode: Int, permissions: Array&lt;out String&gt;, grantResults: IntArray) {<br>    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {<br>    <br>    }<br>}</pre><p>最後記得在onCreate()或onStart()時呼叫verifyStoragePermission()，開始取得權限的流程。</p><pre>@RequiresApi(Build.VERSION_CODES.O)<br>override fun onStart() {<br>   super.onStart()<br>   verifyStoragePermission()<br>}</pre><h4>取得裝置的最後位置座標</h4><p>接下來我們要使用 <strong>Google Play services client library </strong>取得手機最後位置的座標。</p><blockquote>The Google Play services APK contains the individual Google services and runs as a background service in the Android OS. You interact with the background service through the client library and the service carries out the actions on your behalf.</blockquote><p>依照官方的說明，我們知道這個library是與在Android手機背景執行的Google service互動，藉此得到位置資訊。利用client library提供的類別，我們就可以得到相關的物件。</p><p>使用前記得先在buid.gradle(app)加入library：</p><pre>implementation &#39;com.google.android.gms:play-services-location:15.0.1&#39;</pre><p>要取得裝置最後位置的座標，需使用到FusedLocationProviderClient object，這個物件會提供較精確的最後位置資訊。呼叫LocationServices.getFusedLocationProviderClient(Context)</p><p>得到location provider client後呼叫它的 <em>getLastLocation()</em>，這個方法會回傳 Task object，Task是專門處理非同步工作的類別，它的作用是只要長時間的工作一旦完成，就會呼叫OnSuccessListener的onSuccess()，保證使用者能夠在此方法內得到工作回傳的結果。</p><p>因此我們需要先建個OnSuccessListener object，並實作onSuccess()方法。onSuccess()會在取得最後位置的工作完成後被呼叫，並取得location object。所以我們要在這個方法內實作取得locationc後要做的動作。</p><p>建立完在Task.addOnSuccessListener(OnSuccessListener)方法中傳入OnSuccessListener object。</p><pre>fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)</pre><pre>fusedLocationClient.lastLocation?.addOnSuccessListener { <br>location: Location? -&gt;<br>   lastLocation = location // get Location object<br>}</pre><h4>利用座標取得實際地址</h4><p>當取得擁有座標屬性的Location object後，我們要藉由 IntentService 執行取得<strong>實際地址</strong>的工作，並將結果傳回Activity。</p><p>首先建立一個新類別繼承 <em>ResultReceiver</em> ，這個類別負責接收由背景service傳來的查詢地址結果。</p><pre>internal inner class AddressResultReceiver(handler: Handler) : ResultReceiver(handler) {<br>    override fun onReceiveResult(resultCode: Int, resultData: Bundle?) {<br>      super.onReceiveResult(resultCode, resultData)<br>      Timber.d(&quot;onReceiveResult: resultCode: ${resultCode}    resultData: ${resultData}&quot;)</pre><pre>      locationAddress =   resultData?.getString(Constants.RESULT_DATA_KEY) ?: &quot;&quot;</pre><pre>      Timber.d(&quot;locationAddress: ${locationAddress}&quot;)<br>      // show message if an address was found<br>      if (resultCode == Constants.SUCCESS_RESULT) {<br>      Toast.makeText(this@MainActivity, &quot;定位完成&quot;,      Toast.LENGTH_SHORT).show()<br>      }<br>   }<br>}</pre><p>再來建立一個繼承IntentService的FetchAddressIntentService class。IntentService是一種可以在背景工作的元件，與一般Service不同的地方在於它自動建立執行緒，而且當工作執行完後會自動銷毀，不需要呼叫stopSelf()或是stopService()。在Activity呼叫startService(intent)時，會開始執行service的onStartCommand()，將intent排入隊列中。每次只會有一個 intent 傳入 onHandleIntent() callback method，我們要在此方法取得Address object。</p><pre>override fun onHandleIntent(intent: Intent?) {</pre><pre>if (intent != null) {</pre><pre>Log.d(TAG, &quot;onHandleIntent: ${intent}&quot;)</pre><pre>// Pass a Locale object to the Geocoder object to ensure that the resulting address is localized to the user&#39;s geographic region</pre><pre>receiver = intent.getParcelableExtra(Constants.RECEIVER)</pre><pre>val geocoder = Geocoder(this, Locale.getDefault())</pre><pre>var errorMessage = &quot;&quot;</pre><pre>// Get the location passed to this service through an extra.</pre><pre>val location = intent.getParcelableExtra&lt;Location&gt;(Constants.LOCATION_DATA_EXTRA)</pre><pre>Log.d(TAG, &quot;onHandleIntent: location: ${location}&quot;)</pre><pre>// Ready-only empty list</pre><pre>var address = emptyList&lt;Address&gt;()</pre><pre>try {</pre><pre>// Just get single address</pre><pre>address = geocoder.getFromLocation(location.latitude, location.longitude, 1)</pre><pre>} catch (ioException: IOException) {</pre><pre>errorMessage = getString(R.string.service_not_available)</pre><pre>} catch (illegalArgumentException: IllegalArgumentException) {</pre><pre>errorMessage = &quot;Use invalid longitude and latitude&quot;</pre><pre>}</pre><pre>if(address.isEmpty()) {</pre><pre>// If address is empty, pass error message to receiver.</pre><pre>if (errorMessage.isEmpty()) {</pre><pre>errorMessage = &quot;no address found&quot;</pre><pre>}</pre><pre>// deliver</pre><pre>deliverResultReceiver(Constants.FAILURE_RESULT, errorMessage)</pre><pre>} else {</pre><pre>// If address isn&#39;t empty,</pre><pre>val address = address[0]</pre><pre>// Fetch the</pre><pre>val addressFragment = with(address) {</pre><pre>(0..maxAddressLineIndex).map { getAddressLine(it) }</pre><pre>}</pre><pre>deliverResultReceiver(Constants.SUCCESS_RESULT, addressFragment.joinToString(separator = &quot;\n&quot;))</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>依照上面程式碼，取得address object後再建立一個方法叫 deliverResultReceiver()，由此方法負責傳送結果給我們前面在activity建立的AddressResultReceiver object。</p><pre>// send the results back to the requesting activity</pre><pre>private fun deliverResultReceiver(resultCode: Int, message:String) {</pre><pre>val bundle = Bundle().apply { putString(Constants.RESULT_DATA_KEY, message) }</pre><pre>Log.d(TAG, &quot;deliverResultReceiver bundle: ${bundle}&quot;)</pre><pre>// send() will call onReceiveResult()</pre><pre>receiver?.send(resultCode, bundle)</pre><pre>}</pre><p>最後一個步驟是回到Activity並建立方法 startIntentService()。在這個方法內開始一個在背景執行的 service來幫我們將<strong>位置的經緯度</strong>轉換成想要的<strong>實際地址</strong>。</p><pre>fun startIntentService() {</pre><pre>Log.d(TAG, &quot;start intentService&quot;)</pre><pre>val intent = Intent(this, FetchAddressIntentService::class.java).apply {</pre><pre>resultReceiver = AddressResultReceiver(Handler())</pre><pre>putExtra(Constants.RECEIVER, resultReceiver)</pre><pre>Log.d(TAG, &quot;start intentService lastLocation: ${lastLocation}&quot;)</pre><pre>putExtra(Constants.LOCATION_DATA_EXTRA, lastLocation)</pre><pre>}</pre><pre>// Starts intent service to get address in background.</pre><pre>startService(intent)</pre><pre>}</pre><h4>內嵌Google地圖</h4><p>首先在gradle.build(app)加入library：</p><pre>implementation ‘com.google.android.gms:play-services-maps:15.0.0’</pre><p>Google Map API已經提供了 <em>SupportMapFragment </em>可以讓你直接加地圖到Activity。我們可以直接在xml加入地圖的fragment或是在程式碼的 onCreate 區塊加入。</p><pre>&lt;fragment xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</pre><pre>android:id=&quot;@+id/fragment_map&quot;</pre><pre>android:name=&quot;com.google.android.gms.maps.SupportMapFragment&quot;</pre><pre>android:layout_width=&quot;match_parent&quot;</pre><pre>android:layout_height=&quot;match_parent&quot;</pre><pre>tools:context=&quot;com.york.android.cafemap.view.MapsActivity&quot; /&gt;</pre><p>加完之後為了取得GoogleMap object，Activity要實作<em>OnMapReadyCallback</em>，因此就能在 <em>onMapReady(p0: GoogleMap?) </em>這個callback method得到 GoogleMap object。</p><h4>啟動Google Map App來導航</h4><p>依照官方文件的範例，依規定建立一個包含座標或是住址的字串並用Uri.parse(String)轉成Uri。</p><pre>// Create a Uri from an intent string. Use the result to create an Intent.<br>Uri gmmIntentUri = Uri.parse(&quot;google.streetview:cbll=46.414382,10.013988&quot;);</pre><p>再建立intent並傳入ACTION_VIEW及Uri object 。</p><pre>// Create an Intent from gmmIntentUri. Set the action to ACTION_VIEW</pre><pre>Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);</pre><p>設定要啟動App的package name，限制intent所能啟動的App。</p><pre>// Make the Intent explicit by setting the Google Maps package</pre><pre>mapIntent.setPackage(&quot;com.google.android.apps.maps&quot;);</pre><p>傳入startActivity(intent)。</p><pre>// Attempt to start an activity that can handle the Intent</pre><pre>startActivity(mapIntent);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ff82ba2682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[探討Android的介面尺寸單位]]></title>
            <link>https://kmgs4524.medium.com/%E6%8E%A2%E8%A8%8Eandroid%E7%9A%84%E4%BB%8B%E9%9D%A2%E5%B0%BA%E5%AF%B8%E5%96%AE%E4%BD%8D-32907bfc74f4?source=rss-6e154a228566------2</link>
            <guid isPermaLink="false">https://medium.com/p/32907bfc74f4</guid>
            <dc:creator><![CDATA[York]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 01:21:22 GMT</pubDate>
            <atom:updated>2018-06-08T01:22:02.352Z</atom:updated>
            <content:encoded><![CDATA[<p>這次要介紹的是Android設計介面會用到的單位dp、px，兩者之間有何差異及如何轉換。</p><h4><strong>何謂 px、dp、dpi ?</strong></h4><p><strong>px(Pixel) 像素</strong></p><p>px是pixel的簡寫，中文稱作像素，也就是螢幕上實際的像素點單位。因此解析度為1920 x 1080的畫面代表長有1920個像素點，寬有1080個像素點，而面積就是1920 x 1080個像素點。</p><p><strong>ppi( Pixels Per Inch)</strong></p><p>ppi的意思就是每一英吋有幾個像素點，另一種講法就是像素密度。假設有個螢幕的長寬都是1英吋，長寬各有10個像素點，因此我們就能說這個這個螢幕的解析度為10ppi。但例子若改成這個螢幕長寬一樣是1英吋，而長寬各有20個像素點，那麼它的解析度就是20ppi。因此我們發現同樣尺寸的螢幕，ppi越高的話，像素點就越小，畫面看起來也就越精細。</p><p>註：1英吋 = 2.54公分</p><h4><strong>Android的尺寸單位</strong></h4><p>然而Android的手機有太多種尺寸、不同的尺寸的解析度都不太一樣。因此若是使用px(像素)為單位設計元件大小的話，會發生一個200 <strong>px</strong> x 200 <strong>px</strong> 的按鈕在低解析度的畫面(例如320 x 480)會非常的大，而在高解析度(例如1920 x 1080)的畫面上卻又很小的情況。因此在設計Android的介面時就使用單位<em>dp </em>來解決這問題。</p><p><strong>dp ( Density-Independent Pixel ) &amp; dpi( dots per inch )</strong></p><p>在介紹什麼是dp之前，首先我們先介紹什麼是dpi。其實dpi跟前面介紹的ppi是同樣的原理，只是Google用不同的名稱來定義。首先看這張圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bcSBZ_wXufGEyVRC" /></figure><p>Android的每間廠牌手機的尺寸與密度都不一樣，於是Google定義了一套規格來規範幾種螢幕的密度單位：</p><ul><li>mdpi：像素密度為160 dpi。</li><li>hdpi：像素密度為 240 dpi。</li><li>xhdpi：像素密度為 360 dpi。</li><li>xxhdpi：像素密度為 480 dpi。</li><li>xxxhdpi：像素密度為 640 dpi。</li></ul><p>為了讓同個元件在不同密度的螢幕上看起來大小都一樣，Google以dpi定義了單位 <strong>dp </strong>，來確保開發人員在建立介面元件時，使用這個單位所設的長寬在不同密度的螢幕上的大小都一致。例如我們假設下圖的字母 a 的長和寬都是100dp，我們分別有兩支手機的螢幕密度為160 dpi 和密度為320 dpi ，那麼縱使它們的密度不同，字母 a 在兩支手機畫面上的大小依然會相同。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*BEP2wGqTA5gAu49l" /><figcaption>來源：https://developer.android.com/guide/practices/screens_support</figcaption></figure><p>總結來說，要釐清各單位之間重點在於</p><ul><li>dpi，也就是像素密度。越大代表畫面的像素點越多，但是像素點也較小；反之dpi越小代表畫面的像素點越少，但像素點也較大。</li><li>呈上點，所以同樣長寬100dp的按鈕在160 dpi 的螢幕上是尺寸是 100 <strong>px</strong> x 100 <strong>px</strong>，但在 320 dpi 的螢幕上的尺寸是 200 <strong>px </strong>x 200 <strong>px </strong>。雖然長寬的值變兩倍了，但是密度也相差兩倍。</li></ul><p>白話一點來說，當兩個螢幕密度比例為兩倍時，若是要在高密度螢幕上的按鈕看起來跟低密度的螢幕上的大小一樣的話，高密度上的按鈕長寬(以像素為單位)的值就必須是低密度的兩倍。</p><p><strong>單位轉換</strong></p><p>px 與 dp 單位之間的轉換公式：</p><p>pixel = dp x ( density (dpi)/ 160)</p><p>Android有提供dp與px的轉換比例：</p><pre>val scale = context.resources.displayMetrics.density</pre><pre>val widthInPx = widthInDp * scale</pre><p><strong>取得螢幕解析度(像素)</strong></p><p>有兩種方式能取得手機的螢幕解析度：</p><ul><li>resources.displayMetrics</li></ul><pre>val displayMetrics = context.resources.displayMetrics</pre><pre>val height = displayMetrics.heightPixels</pre><pre>val width = displayMetrics.widthPixels</pre><ul><li>windowManager.defaultDisplay</li></ul><pre>val defaultDisplayMetrics = DisplayMetrics()</pre><pre>(context as AppCompatActivity).windowManager.defaultDisplay.getMetrics(defaultDisplayMetrics)</pre><pre>val height = displayMetrics.heightPixels</pre><pre>val width = displayMetrics.widthPixels</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*ymkqQMVGhkHK9jXO" /></figure><p><strong>參考連結：</strong></p><p><a href="https://developer.android.com/guide/practices/screens_support">Screen compatibility overview | Android Developers</a></p><p><a href="https://medium.com/uxabc/understanding-ui-units-8acdc0575388">https://medium.com/uxabc/understanding-ui-units-8acdc0575388</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32907bfc74f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>