<?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[Android Development by Danylo :) - Medium]]></title>
        <description><![CDATA[This is a publication about Android development - Medium]]></description>
        <link>https://medium.com/android-development-by-danylo?source=rss----b1baad4cfa74---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Android Development by Danylo :) - Medium</title>
            <link>https://medium.com/android-development-by-danylo?source=rss----b1baad4cfa74---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:12:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/android-development-by-danylo" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10 steps to create a custom LayoutManager]]></title>
            <link>https://medium.com/android-development-by-danylo/10-steps-to-create-a-custom-layoutmanager-2f30ab2f979d?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/2f30ab2f979d</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[layoutmanager]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:30:18 GMT</pubDate>
            <atom:updated>2016-01-11T22:08:14.680Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is based on my github project <a href="https://github.com/danylovolokh/LondonEyeLayoutManager">LondonEyeLayoutManager</a>, recently published in <a href="http://androidweekly.net/issues/issue-183">Android Weekly</a>. For the sake of simplicity code snippets here might be different from the code in repository.</p><p><strong>What we normally do in order to have this kind of functionality that ListView provides? We have to:</strong></p><ol><li>Know how to lay out views on the screen.</li><li>Handle touch events, measure scroll velocity and direction.</li><li>Move views on the screen when scroll is happening.</li><li>Implement views recycling.</li></ol><p><strong>With a new RecyclerView &amp; LayoutManager few of these point are handled for us</strong>:</p><p>1. We don’t have to handle touch events, measure scroll velocity and direction.</p><p>LayoutManager provides very convenient API for that:</p><pre><a href="http://twitter.com/Override">@Override</a><br>public int scrollVerticallyBy(<br>    int dy, <br>    RecyclerView.Recycler recycler, <br>    RecyclerView.State state) {</pre><pre>return 0; <strong>// actual scrolled distance</strong></pre><pre><a href="http://twitter.com/Override">@Override</a><br>public int scrollHorizontallyBy(<br>    int dx, <br>    Recycler recycler, <br>    State state) {</pre><pre>return 0; <strong>// actual scrolled distance</strong></pre><p>This API has a drawback : we only get vertical or horizontal scroll. If we need to know if user, for example scrolls diagonally we should calculate it by ourselves. These methods gives us a value by which we should move views on the screen. We should return the actual distance <strong>(in pixels)</strong> by which we moved our views.</p><p>For example:</p><p><strong>scrollVerticallyBy(dy, recycler, state) </strong>was called with dy = 25;</p><p>But to the end of a screen we have left 20 pixels. So we move a views by -20px and return -20. You should notice that we are returning a value with an opposite sign.</p><p>LayoutManger will “understand” that if we returned less than was scrolled, it should stop sending us these scroll events, we already reached the end. Demo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*sXmRlEvM7P-AasPOoE2gqg.gif" /></figure><p>It also means that if we return “0” the list will not be scrolled at all.</p><p>2. We don’t have to handle recycling.</p><p>If we need a view on position we just call the appropriate method from the <strong>Recycler.</strong></p><pre>View newView = recycler.getViewForPosition(position);</pre><pre>....</pre><pre>recycler.recycleView(viewToRecycle);</pre><p><strong>This is what we have to implement:</strong></p><ol><li>Layout views on the screen.</li><li>Move views on the screen when scroll is happening.</li></ol><h3>Let’s start implementing our LayoutManager.</h3><p><strong>Goal: Create a LayoutManager that will layout our views on the circular trajectory.</strong></p><p>Requirements:</p><ol><li>Layout in first quadrant. (Y axis in Android is points to the opposite direction than in <strong>Cartesian coordinate system</strong>).</li><li>Views center should keep it’s center on the circle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*xHqHw_JE7JxJqCLh-GFuCw.gif" /></figure><p>Here is how we are going to do that :</p><p><strong>10 steps to implement a LayoutManager.</strong></p><p>As I mentioned earlier there is <strong>two things </strong>that we need to handle: layout views and handle scrolling.</p><p><strong>5 steps to handle layout of views:</strong></p><ol><li>Get view by position.</li><li>Add view to the RecyclerView.</li><li>Get view location on the screen.</li><li>Layout this view.</li><li>Increment view position.</li></ol><p>Run it in the loop until we layout a view that will be partially visible. It will be indicator that we’re done.</p><p><strong>5 steps to handle scrolling:</strong></p><ol><li>Calculate views offset by received scroll value (dx, dy).</li><li>Calculate new position of a view using received offset.</li><li>Change view location.</li><li>Recycle views that become invisible when they were moved.</li><li>Add views to empty space created by moved views if needed.</li></ol><p>Perform these operation on each call of <strong>scrollVerticallyBy.</strong></p><p>And of course these 10 operation are very abstract. We have to do a lot of additional job in order to make it work :) Sorry</p><p><strong>Creating the circle</strong></p><p>In order to lay out and move views on the circular trajectory we have to create a set of predefined points which will be the center of views. Having this will give us very useful functionality:</p><p>When scroll is happening we don’t have to calculate the point on the circle to which we need move the view. We just get index of point that is center of view and increase this index by received scroll offset, a point on the position of increased index will be new center of view.</p><p>Points should be located with pixel-pixel precision, that’s why we cannot use “the circle equation” nor the sine/cosine to create points. We will use<a href="https://en.wikipedia.org/wiki/Midpoint_circle_algorithm"> <strong>Mid point circle algorithm</strong></a> to create points but modified a bit.<strong><em> (From now on I will describe the implementation assuming that reader knows how Mid point algorithm works)</em></strong></p><p>Here is an original algorithm copy-pasted from Wikipedia:</p><pre>void DrawCircle(int x0, int y0, int radius)<br>{<br>  int x = radius;<br>  int y = 0;<br>  int decisionOver2 = 1 - x;   <em>// Decision criterion divided by 2 evaluated at x=r, y=0</em><br><br>  <strong>while</strong>( y &lt;= x )<br>  {<br>    DrawPixel( x + x0,  y + y0); <em>// Octant 1</em><br>    DrawPixel( y + x0,  x + y0); <em>// Octant 2</em><br>    DrawPixel(-x + x0,  y + y0); <em>// Octant 4</em><br>    DrawPixel(-y + x0,  x + y0); <em>// Octant 3</em><br>    DrawPixel(-x + x0, -y + y0); <em>// Octant 5</em><br>    DrawPixel(-y + x0, -x + y0); <em>// Octant 6</em><br>    DrawPixel( x + x0, -y + y0); <em>// Octant 8</em><br>    DrawPixel( y + x0, -x + y0); <em>// Octant 7</em><br>    y++;<br>    <strong>if</strong> (decisionOver2&lt;=0)<br>    {<br>      decisionOver2 += 2 * y + 1;   <em>// Change in decision criterion for y -&gt; y+1</em><br>    }<br>  <strong> </strong> else<br>    {<br>      x--;<br>      decisionOver2 += 2 * (y - x) + 1;   <em>// Change for y -&gt; y+1, x -&gt; x-1</em><br>    }<br>  }<br>}</pre><p>This algorithm is creating all 8 octants in parallel. It means that created views in the list will be in following order:</p><p>(x1, y1) — 1st Octant (Black)</p><p>(x2, y2) — 2nd Octant (Blue)</p><p>(x3, y3) — 3rd Octant (Dark Grey)</p><p>(x4, y4) — 4th Octant (Cyan)</p><p>(x5, y5) — 5th Octant (Green)</p><p>(x6, y6) — 6th Octant (Pink)</p><p>(x7, y7) — 7th Octant (Yellow)</p><p>(x8, y8) — 8th Octant (Red)</p><p>And here is the problem: if the center of a view is on first point (x1, y1) and received offset from <strong>scrollVerticallyBy(int dy, Recycler recycler) </strong>is <strong>dy=3 </strong>we should move our view by 3 points which means move to point (x4, y4). And point (x4, y4) is in 4th octant. But it should be just moved by few pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*vs9qhTPlfsje5bQ8z5gRnA.gif" /></figure><p>To have the list in consecutive order to easily get next or previous point on the circle. So the algorithm has to be modified:</p><ol><li>Create first octant points using <strong>Mid point algorithm.</strong></li><li>Mirror points on 2nd octant using points from 1st octant. (after this action we have a points of 1st quadrant).</li><li>MIrror points on the 2nd quadrant using points from 1st quadrant(after this action we have a points of 1st semicircle).</li><li>Mirror points on the 2nd semicircle using points from 1st semicircle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*LU_w5wkwoFqcyboByibpsA.gif" /></figure><p>And right now the points are created consecutively:</p><p>(x1, y1) — 1st Octant (Pink)</p><p>(x2, y2) — 2nd Octant (Pink)</p><p>(x3, y3) — 3rd Octant (Pink)</p><p>(x4, y4) — 4th Octant (Pink)</p><p>(x5, y5) — 5th Octant (Pink)</p><p>(x6, y6) — 6th Octant (Pink)</p><p>(x7, y7) — 7th Octant (Pink)</p><p>(x8, y8) — 8th Octant (Pink)</p><p>And if while scrolling we get <strong>dy=3 </strong>then our view will be moved correctly.</p><p>Here is the sample application: <a href="https://github.com/danylovolokh/MidPointCircleExplained">https://github.com/danylovolokh/MidPointCircleExplained</a></p><p>The same code is used in LondonEyeLayoutManager. We have an abstraction called <strong>CircleMirrorHelper </strong>that gives the API to perform points mirroring.</p><pre>public interface CircleMirrorHelper {</pre><pre>void mirror_2nd_Octant(<br>            Map&lt;Integer, Point&gt; circleIndexPoint,<br>            Map&lt;Point, Integer&gt; circlePointIndex<br>    );</pre><pre>void mirror_2nd_Quadrant(<br>            Map&lt;Integer, Point&gt; circleIndexPoint,<br>            Map&lt;Point, Integer&gt; circlePointIndex<br>    );</pre><pre>void mirror_2nd_Semicircle(<br>            Map&lt;Integer, Point&gt; circleIndexPoint,<br>            Map&lt;Point, Integer&gt; circlePointIndex<br>    );</pre><pre>}</pre><p>And there is a concrete implementation <strong>FirstQuadrantCircleMirrorHelper </strong>that “knows” how to mirror points in our “concrete” first quadrant.</p><pre>public class FirstQuadrantCircleMirrorHelper implements CircleMirrorHelper {</pre><pre>// relevant code here</pre><pre>}</pre><p>You may notice a strange signature of methods. Points are added into two maps. It is done to easily perform following operation:</p><p>When scroll is happening we get the center point of a view and use it as a key to get an index of this point. We increase(or decrease, depends on the scroll direction) the index by the received value from <strong>scrollVerticallyBy(dy, recycler, state) </strong>and use this index as a key to get a new point that will be center of a view.</p><p>It would look a lot simpler if it would be <strong>List&lt;Point&gt; </strong>but it was done for the sake of performance. It is faster to get “index by point” when we have a Map of them.</p><h4><strong>Layouting the views.</strong></h4><p>To get quadrant specific stuff there is an abstraction called <strong>QuadrantHelper.</strong></p><pre>/** This is generic interface for quadrant related          <br> * functionality.<br> *<br> * To lay out in each quadrant you should implement quadrant-<br> * specific classes :<br> * {<a href="http://twitter.com/link">@link</a> FirstQuadrantHelper}<br> */<br>public interface QuadrantHelper {<br> <br>   Point findNextViewCenter(ViewData previousViewData, int     nextViewHalfViewWidth, int nextViewHalfViewHeight);</pre><pre>    int getViewCenterPointIndex(Point point);</pre><pre>    Point getViewCenterPoint(int newCenterPointIndex);</pre><pre>    int getNewCenterPointIndex(int newCalculatedIndex);<br>    <br>    Point findPreviousViewCenter(ViewData nextViewData, int previousViewHalfViewHeight);</pre><pre>    boolean isLastLayoutedView(int recyclerHeight, View view);<br>    <br>    int checkBoundsReached(int recyclerViewHeight, int dy, </pre><pre>    View firstView, View lastView, boolean isFirstItemReached, boolean isLastItemReached);</pre><pre>    int getOffset(int recyclerViewHeight, View lastView);<br>}</pre><p>And there is a concrete implementation <strong>FirstQuadrantHelper.</strong></p><pre>public class FirstQuadrantHelper implements QuadrantHelper {</pre><pre><strong>// code here :)</strong></pre><pre>}</pre><p>LayoutManager forces us to implement only one method</p><pre><a href="http://twitter.com/Override">@Override</a><br>public RecyclerView.LayoutParams generateDefaultLayoutParams() {<br>return new RecyclerView.LayoutParams(<br>                RecyclerView.LayoutParams.WRAP_CONTENT,<br>                RecyclerView.LayoutParams.WRAP_CONTENT);<br>}</pre><p>But we need to override a few more, the most important is <strong>onLayoutChildren</strong>:</p><pre>private Layouter mLayouter;</pre><pre><a href="http://twitter.com/Override">@Override</a><br>public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {</pre><pre><strong>// some code here...</strong></pre><pre>// It will be our stop flag<br>boolean isLastLayoutedView;</pre><pre>do{<br><strong>// 1. get view by position</strong><br>View view = recycler.getViewForPosition(mLastVisiblePosition);</pre><pre><strong>// 2. add view to the recycler view</strong><br>addView(view);</pre><pre><strong>// 3. get view location on the screen.<br>// 4. layout this view<br>// Points 3 and 4 are performed by &quot;Layouter&quot;</strong><br>viewData = mLayouter.layoutNextView(view, viewData);</pre><pre>isLastLayoutedView = mLayouter.isLastLaidOutView(view);</pre><pre><strong>// 5. increment view position</strong><br>mLastVisiblePosition++;</pre><pre><strong>// we do this until we laid out last visible view</strong><br>} while (!isLastLayoutedView &amp;&amp; mLastVisiblePosition &lt; itemCount);</pre><pre>}</pre><p><strong>Layouter </strong>used<strong> </strong>in this code snippet is an entity that uses <strong>QuadrantHelper </strong>to get some information about the views location in concrete quadrant (<strong>FirstQuadrantHelper </strong>in our case) and provide following API to LayoutManager:</p><pre><strong>// This method is using a data from previous view in order to <br>// layout the next view with pixel precision to the previous</strong></pre><pre>public ViewData layoutNextView(View view, ViewData previousViewData);</pre><pre><strong>// This method is using a data from next view in order to <br>// layout the previous view with pixel precision to the <br>// previous</strong></pre><pre>public ViewData layoutViewPreviousView(View view, ViewData previousViewData);</pre><pre><strong>// This method checks if view is the last visible view on the screen</strong></pre><pre>public boolean isLastLaidOutView(View view);</pre><p>Let’s explain<strong> layoutNextView.</strong></p><pre>public ViewData layoutNextView(View view, ViewData previousViewData) {</pre><pre>int halfViewHeight;<br>int halfViewWidth;</pre><pre><strong>// measure view and get a half of it&#39;s height &amp; width<br>// QuadrantHelper uses it to find next view center</strong></pre><pre>Point viewCenter = mQuadrantHelper.findNextViewCenter(previousViewData, halfViewHeight, halfViewWidth);</pre><pre><strong>// Layouter uses callback to LayoutManager to perform layout</strong></pre><pre>int left, top, right, bottom;<br><strong>// calculate values using viewCenter</strong></pre><pre><strong>// layout view using method layoutDecorated from LayoutManager</strong><br>mLayoutManagerCallback.layoutDecorated(view, left, top, right, bottom);</pre><pre>return viewData of just laid out view.</pre><pre>}<br></pre><p><strong>layoutNextView</strong> takes <strong>previousViewData </strong>as a parameter. On the first start previousViewData is:</p><pre>ViewData viewData = new ViewData(0, 0, 0, 0,<br>    mQuadrantHelper.getViewCenterPoint(0)<br>);</pre><p>After we implement <strong>onLayoutChildren </strong>we have views layouted on the screen, but without scrolling, recycling and other stuff for which we need RecyclerView.</p><h4><strong>Handle scrolling</strong></h4><p>To do this we have to override <strong>scrollVerticallyBy </strong>and/or<strong> scrollHorizontallyBy </strong>and also return “true” from <strong>canScrollVertically </strong>and/or <strong>canScrollHorizontally.</strong></p><p>In our case we only handle vertical scroll.</p><pre><a href="http://twitter.com/Override">@Override</a><br>public boolean canScrollVertically() {<br>    return true;<br>}</pre><pre><a href="http://twitter.com/Override">@Override</a><br>public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state){</pre><pre>int childCount = getChildCount();<br>if (childCount == 0) {<br>    <strong>// we cannot scroll when there is no views</strong><br>    return 0;<br>}</pre><pre>return mScroller.scrollVerticallyBy(dy, recycler);<br>}</pre><p>We have generic interface <strong>IScrollHandler</strong> and two implementations : <strong>PixelPerfectScrollHandler </strong>and <strong>NaturalScrollHandler. </strong>Each of these has their advantages and drawbacks.</p><p>Scroll handler also uses <strong>QuadrantHelper </strong>to get data specific for concrete quadrant.</p><pre>public interface IScrollHandler {</pre><pre>int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler);</pre><pre>}</pre><p>On the first look scrolling looks pretty simple : you just get the <strong>dy</strong> and move every view by this value, but this is not the case.</p><p><strong>NaturalScrollHandler</strong></p><p>Why “Natural” ? Because when views are scroller it looks very natural. Distance between center of views is kept.</p><p>Using this scroll handler views each view will be moved by the same distance (<strong>dy</strong>) on the circle which looks great when views has distance between them and they are square shaped:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*5jaWSU7bdXVPg90m141VNA.gif" /></figure><p>But when there are no gaps between views they will overlap each other or visual distance between them will be getting bigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*jc3SYyttwXmwlfm5J3qHYQ.gif" /></figure><p>Here is the code:</p><p>In this scroller we can omit first point : <strong>Calculate views offset by received scroll value (dx, dy), </strong>because our offset is dy.</p><pre>public class NaturalScrollHandler //..</pre><pre>public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler){</pre><pre>for (int indexOfView = 0; indexOfView &lt;    mCallback.getChildCount(); indexOfView++) {</pre><pre>    View view = mCallback.getChildAt(indexOfView); <br><strong>     // Points 1, 2, 4 here</strong><br>    scrollSingleViewVerticallyBy(view, delta);<br>}</pre><pre><strong>// after scrolling perform recycling<br>// Points 4,5 here</strong></pre><pre>performRecycling();</pre><pre>}</pre><pre><strong>/**<br> * This method calculates new position of single view and  <br> * returns new center point of the view<br> */<br></strong>protected Point scrollSingleViewVerticallyBy(View view, int indexOffset) {</pre><pre><strong>// find view center using view properties</strong><br>int viewCenterX = view.getRight() - view.getWidth() / 2;<br>int viewCenterY = view.getTop() + view.getHeight() / 2;</pre><pre><strong>//this object will be updated many times during search of view</strong><br>SCROLL_HELPER_POINT.update(viewCenterX, viewCenterY);</pre><pre>int centerPointIndex = mQuadrantHelper.getViewCenterPointIndex(SCROLL_HELPER_POINT);</pre><pre><strong>// increase the point by indexOffset</strong><br>int newCenterPointIndex = mQuadrantHelper.getNewCenterPointIndex(centerPointIndex + indexOffset);</pre><pre><strong>// after increasing index, find point by index<br>// 2. Calculate new position of a view using received offset.</strong></pre><pre>Point newCenterPoint = mQuadrantHelper.getViewCenterPoint(newCenterPointIndex);</pre><pre><strong>// calculate dy and dx</strong><br>int dx = newCenterPoint.getX() - viewCenterX;<br>int dy = newCenterPoint.getY() - viewCenterY;</pre><pre><strong>// 3. Change view location.</strong><br>view.offsetTopAndBottom(dy);<br>view.offsetLeftAndRight(dx);</pre><pre>return newCenterPoint;</pre><pre>}</pre><p>Method <strong>performRecycling </strong>is also responsible for filling the gap created by moved views.</p><pre><strong>/**<br>* This method recycles views:<br>* If views was scrolled down then it recycles top if needed <br>* and add views from the bottom<br>* If views was scrolled up then it recycles bottom if needed <br>* and add views from the top<br>* </strong><a href="http://twitter.com/param"><strong>@param</strong></a><strong> delta - indicator of scroll direction<br>*/</strong><br>private void performRecycling(int delta, View firstView, View       lastView,  RecyclerView.Recycler recycler) {<br><br>if (delta &lt; 0) {<br>    <strong>/** Scroll down*/</strong><br><strong>    // 4. Recycle views that become invisible when they were <br>    // moved.<br></strong>    recycleTopIfNeeded(firstView, recycler);<br> <br><strong>    // 5. Add views to empty space created by moved views if<br>    // needed.<br></strong>    addToBottomIfNeeded(lastView, recycler);</pre><pre>} else {<br>    <strong>/** Scroll up*/</strong><br>    <strong>// 4. Recycle views that become invisible when they were <br>    // moved.<br>    </strong>recycleBottomIfNeeded(lastView, recycler);</pre><pre><strong>    // 5. Add views to empty space created by moved views if<br>    // needed.<br></strong>    addTopIfNeeded(firstView, recycler);<br>}<br>}</pre><p>Because of inability of <strong>NaturalScrollHandler </strong>to be used with non-square views I’ve decided to implement another one.</p><p><strong>PixelPerfectScrollHandler</strong></p><p>PixelPerfectScrollHandler was designed to follow two rules while scrolling.</p><p>This scroll handler keeps view in touch when scrolling. 1. Views center is on the circle 2. Views edges are always in touch with each other. Sometimes these requirements are making views “jump” when scroll: If “view B” is below “view A” and views are scrolled down we can reach a point in which “view B” cannot longer stay below “view A” and keep it’s center on the circle so, in this case “view B” jumps to the side in order to stay in touch with “view A” side by side and keep it’s center on the circle. The logic: 1. Scroll first view by received offset. 2. Calculate position of other views relatively to first view.</p><p>Here is a demo of how the “jump” looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*HJJVKz895MfyRZ6VHPzLzg.gif" /></figure><pre>public class PixelPerfectScrollHandler//...</pre><pre><strong>//..</strong></pre><pre>public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler){</pre><pre>// <strong>1. Calculate views offset by received scroll value dy.</strong><br>int delta;<br><strong>// calculate delta. Look if we reached bottom or top of the <br>// list If yes then return actual distance on which we have <br>// moved views</strong></pre><pre>// <strong>2.Calculate new position of a view using received offset.</strong></pre><pre>Point newCenterPoint = mQuadrantHelper.getNewCenterPoint(/*some ars here*/)</pre><pre>int yOffset;<br>int xOffset;</pre><pre><strong>// calcute yOffeset and xOffset using new center point of this view</strong></pre><pre>// <strong>3. Change view location.</strong><br><strong>// calling these methods will cause view to change it position</strong><br>view.offsetTopAndBottom(yOffset);<br>view.offsetLeftAndRight(xOffset);</pre><pre><strong>// Using position of first view now we have to find position of other <br>// views. Because it&#39;s a pixel perfect scroller we have to find a <br>// location which will be right below previous view or to the left of <br>// previous view and still keep it&#39;s center on the circle.</strong></pre><pre><strong>// There is a lot of code here, so please check <br>// {@link PixelPerectScrollHandler#scrollSingleView} for the reference</strong></pre><p>After we done moving views we have to recycle views that were hidden and fill a gap that was created by moved views. We call <strong>performRecycling, </strong>exatly like in the NaturalScrollHandler.</p><h4>And that’s it</h4><p>Of course there is a lot of thing to do :</p><ol><li>Animations support.</li><li>Handle inPrelayout</li><li>Save/Restore instance state</li><li>Handle data set changes</li></ol><p>And also there are bugs in the project. This is basically a PoC and not a full tested and polished library. So everyone are welcome to contribute.</p><p><strong>Summary</strong></p><p>I really understand that showing some snippets of code probably isn’t enough to fully explain of how to implement custom LayoutManager, but I hope it’s helps someone if they would like (or need) to implement something similar.</p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f30ab2f979d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/10-steps-to-create-a-custom-layoutmanager-2f30ab2f979d">10 steps to create a custom LayoutManager</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple way to test asynchronous actions in Android: Service, AsyncTask, Thread, RxJava etc.]]></title>
            <link>https://medium.com/android-development-by-danylo/simple-way-to-test-asynchronous-actions-in-android-service-asynctask-thread-rxjava-etc-d43b0402e005?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/d43b0402e005</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:30:15 GMT</pubDate>
            <atom:updated>2016-01-21T22:33:47.754Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes testing asynchronous actions might be very difficult but in most common cases during Android development it might be done with a very simple technique.</p><p>If you know basics of concurrency you can test asynchronous operations <strong>with a simple wait/notify.</strong></p><p><strong>The task:</strong></p><p>There is a “Login Activity” with a simple login form and an asynchronous request to the server. Request is performed by IntentService in a background. Result is delivered with broadcast.</p><p>Create a test if login is working correctly.</p><p>This is a code of our <strong>LoginActivity</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JWnROYgbrN98vdOYBc2lw.png" /></figure><ol><li>After pressing “Perform Login” button service starts and performs login in background. Response will be sent with a broadcast. The “action” of a result broadcast is also passed to the service.</li><li>In the “<strong>LoginActivity</strong>” the broadcast receiver is registered to listen for the response from the service.</li><li>When response is received the <strong>handleLoginResponse</strong> method is called.</li></ol><p>Here is the relevant code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f973372fff50da2549693f1a2a2489a4/href">https://medium.com/media/f973372fff50da2549693f1a2a2489a4/href</a></iframe><p>To write a test we need to do a few things:</p><ol><li>Create <strong>LoginTestActivity</strong> that extends <strong>LoginActivity </strong>and override <strong>handleResponse</strong> method. When this method is called it means that response is received.</li><li>No need to have this <strong>LoginTestActivity </strong>in production code that why we create a separate build flavor for testing.</li><li>Define <strong>LoginTestActivity </strong>in <strong>AndroidManifest.xml</strong> of the separate flavor.</li><li>Create the actual test.</li></ol><p><strong>LoginTestActivity </strong>is very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6db49d9d8c9045921a7bd4637bbde97/href">https://medium.com/media/b6db49d9d8c9045921a7bd4637bbde97/href</a></iframe><p>This is how our project three looks like with a separate flavor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*5a86PDfa1L4FiP1-hANJlw.png" /></figure><p>And here is the actual test:</p><ol><li>It enters login and password into appropriate fields</li><li>Presses “Perform login” button.</li><li>Waits for asynchronous response with a simple <strong>wait/notify</strong>.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cedc647eb1a3933bc5bcc2f75ed5034/href">https://medium.com/media/1cedc647eb1a3933bc5bcc2f75ed5034/href</a></iframe><p>You should notice the important <strong>wait/notify</strong> calls.</p><p>Because Tests are running in a thread different from main we can easily call</p><pre>synchronized(syncObject){<br>    syncObject.wait();<br>}</pre><p>When response from <strong>LoginService</strong> arrives, our <strong>LoginTestActivity</strong> calls <strong>onHandleResponseCalled </strong>and here we can notify the <strong>syncObject.</strong></p><p><strong>Note: we use the Service to perform asynchronous operation. This technique can be used with any asynchronous operation: AsyncTask, Thread, RxJava.</strong></p><h4>And that’s it. Very simple</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*7EWIGFal2NiZ0JZoHCC32g.png" /></figure><p>All the relevant code is on <a href="https://github.com/danylovolokh/TestAsyncrounousAndroid">GitHub</a></p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43b0402e005" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/simple-way-to-test-asynchronous-actions-in-android-service-asynctask-thread-rxjava-etc-d43b0402e005">Simple way to test asynchronous actions in Android: Service, AsyncTask, Thread, RxJava etc.</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing video playback in a scrolled list (ListView & RecyclerView)]]></title>
            <link>https://medium.com/android-development-by-danylo/implementing-video-playback-in-a-scrolled-list-listview-recyclerview-d04bc2148429?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/d04bc2148429</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:30:10 GMT</pubDate>
            <atom:updated>2016-01-24T17:12:09.911Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will describe how to implement video playback in the list. The same that works in popular applications like Facebook, Instagram or Magisto:</p><h4>Facebook:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*vizszEHcRhlK1MV7nrMSWw.gif" /></figure><h4>Magisto:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*9TcSE9YEENQNIcqCT7d2ww.gif" /></figure><h4>Instagram:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*3Lpr8C613ZfgazADX9eKyQ.gif" /></figure><p>This article is based on the opensource project: <a href="https://github.com/danylovolokh/VideoPlayerManager">VideoPlayerManager</a>.</p><p>All the code and a working sample is there. In this article a lot of things will be skipped, so if someone really needs to understand how it works it’s better to download the source code and read the article with the source code in your IDE. But even without the code this article will be good for understanding with what we are dealing here.</p><h4>Two Problems</h4><p>To implement what is needed we have to solve two problems:</p><ol><li>We have to manage video playback. In Android we have a class MediaPlayer.class that works together with SurfaceView and can playback a video. But it has a lot of drawbacks. We cannot use usual VideoView in the list. VideoView extends SurfaceView, and SurfaceView doesn’t have UI synchronization buffers. All this will lead us to the situation where video that is playing is trying to catch up the list when you scroll it. Synchronization buffers are present in TextureView but there is no VideoView that is based on TextureView in Android SDK version 15. <strong>So we need a view that extends TextureView and works with Android MediaPlayer.</strong> Also almost all methods (prepare, start, stop etc…) from MediaPlayer are basically calling native methods that work with hardware. Hardware can be tricky and if will do any work longer than 16ms (And it sure will) then we will see a lagging list. That’s why need to call them from background thread.</li><li>We also need to know which view on the scrolled list is currently active to switch the playback when user scrolls. So basically we have to track the scroll and define the most visible view if it changes.</li></ol><h4>Managing Video Playback</h4><p>Here we aim to provide following functionality:</p><p>Assume that movie playback is on. User scrolls the list and new item in the list becomes more visible than the one which video is playing. So now we have to stop the existing video playback and start the new one.</p><p>The main functionality is : <strong>stop previous playback, and start the new playback only after the old one stops.</strong></p><p>Here is a video sample of how it works: When you press on the video thumbnail — current video playback stops and the other one starts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*V7cAiFeKurRMTLbZTQtLkA.gif" /></figure><h4>VideoPlayerView</h4><p>First thing that we need to implement is the VideoView based on the TextureView. We cannot use VideoView in scrolling list. <strong>Because video rendering will be messed up if user will scroll our list during playback.</strong></p><p>I’ve divided this task into several parts:</p><ol><li>Created a ScalableTextureView. It’s a descendant of TextureView and it knows how to adjust the SurfaceTexture (on this surface texture the playback is running) and provides few options similar to ImageView scaleType.</li></ol><pre>public enum ScaleType {<br>    <em>CENTER_CROP</em>, <em>TOP</em>, <em>BOTTOM</em>, <em>FILL<br></em>}</pre><p>2. Created VideoPlayerView. This is a descendant of ScalableTextureView and it contains all the functionality related to MediaPlayer.class. This custom view encapsulates MediaPlayer.class and provides an API very similar to VideoView. It has all the methods that are directly calling MediaPlayer : setDataSource, prepare, start, stop, pause, reset, release.</p><h4>Video Player Manager and Messages Handler Thread</h4><p>Video Playback Manager works together with the MessagesHandlerThread that is responsible for calling the methods of MediaPlayer . We need to call the methods like prepare(), start() etc. in a separate thread because they are directly connected to devices hardware. And there were cases when we called MediaPlayer.reset() in the UI thread but something went wrong with the player and this method was blocking the UI thread for almost 4 minutes! That’s why we don’t have to use asynchronous MediaPlayer.prepareAsync, we can use synchronous MediaPlayer.prepare . We are doing everything synchronously in a separate thread.</p><p>A flow related to starting new playback. Here is a few steps to do with MediaPlayer:</p><ol><li>Stop previous playback. It’s done by calling MediaPlayer.stop() method.</li><li>Reset MediaPlayer by calling MediaPlayer.reset() method. We need to do it because in scrolling list your view might be reused and we want to have all resources released.</li><li>Release MediaPlayer by calling MediaPlayer.release() method.</li><li>Clear the instance of MediaPlayer. New MediaPlayer instance will be created when new playback on this view should be started.</li><li>Create instance on MediaPlayer for new most visible view.</li><li>Set the data source for new MediaPlayer by calling MediaPlayer.setDataSource(String url).</li><li>Call MediaPlayer.prepare(). There is no need to use asynchronous MediaPlayer.prepareAsync().</li><li>Call MediaPlayer.start()</li><li>Wait for actual playback to start.</li></ol><p>All these actions are wrapped into Messages that are processed in a separate thread, for example this is Stop message. It calls VideoPlayerView.stop(), which eventually calls the MediaPlayer.stop(). We need custom messages because we can set current state. We know is it Stopping or Stopped or else. It helps us to control which message is now in progress and what can we do about it if we need for example, start new playback.</p><pre>/**<br> * This PlayerMessage calls {@link MediaPlayer#stop()} on the instance that is used inside {@link VideoPlayerView}<br> */<br>public class Stop extends PlayerMessage {<br>    public Stop(VideoPlayerView videoView, VideoPlayerManagerCallback callback) {<br>        super(videoView, callback);<br>    }<br><br>    @Override<br>    protected void performAction(VideoPlayerView currentPlayer) {<br>        currentPlayer.stop();<br>    }<br><br>    @Override<br>    protected PlayerMessageState stateBefore() {<br>        return PlayerMessageState.<em>STOPPING</em>;<br>    }<br><br>    @Override<br>    protected PlayerMessageState stateAfter() {<br>        return PlayerMessageState.<em>STOPPED</em>;<br>    }<br>}</pre><p>If we need to start new playback we simply call a method on VideoPlayerManager. And it adds following set of messages to the MessagesHandlerThread:</p><pre>// pause the queue processing and check current state<br>// if current state is &quot;started&quot; then stop old playback<br>mPlayerHandler.addMessage(new Stop(mCurrentPlayer, this));<br>mPlayerHandler.addMessage(new Reset(mCurrentPlayer, this));<br>mPlayerHandler.addMessage(new Release(mCurrentPlayer, this));<br>mPlayerHandler.addMessage(new ClearPlayerInstance(mCurrentPlayer, this));</pre><pre>// set new video player view</pre><pre>mPlayerHandler.addMessage(new SetNewViewForPlayback(newVideoPlayerView, this));</pre><pre>// start new playback<br>mPlayerHandler.addMessages(Arrays.<em>asList</em>(<br>        new CreateNewPlayerInstance(videoPlayerView, this),<br>        new SetAssetsDataSourceMessage(videoPlayerView, assetFileDescriptor, this), // I use local file for demo<br>        new Prepare(videoPlayerView, this),<br>        new Start(videoPlayerView, this)<br>));<br>// resume queue processing</pre><p>The messages are run synchronously that’s why we can pause the queue processing in any time and post new messages, for example:</p><p>Current movie is in preparing state (MedaiPlayer.prepare() was called, and MediaPlayer.start() is waiting in the queue) and user scrolled the list so we need to start playback on a new view. In this case we :</p><ol><li>Pause queue processing</li><li>Remove all pending messages</li><li>Post “Stop”, “Reset”, “Release”, “Clear Player instance” to the queue. They will run right after we return from “Prepare”</li><li>Post “Create new Media Player instance”, “Set Current Media Player”(this one changes the MediaPlayer object on which our messages are performed), “Set data source”, “Prepare”, “Start”. And this messages will start the playback on the new view.</li></ol><p>OK, so we have the utilities to run the playback in the way we need: Stop previous playback and just then Start the next one.</p><p>Here is the gradle dependency for the library:</p><pre>dependencies {<br>    compile &#39;com.github.danylovolokh:video-player-manager:0.2.0&#39;<br>}</pre><h4>Identifying the most visible view in the list. List Visibility Utils.</h4><p>The first problem was to manage the Video Playback. The second problem is to track which view is the most visible and switch the playback into that view.</p><p>There is an entity called ListItemsVisibilityCalculator and its implementation SingleListViewItemActiveCalculator that does all the job.</p><p>Your model class that is used in adapter must implement ListItem interface in order to calculate visibility of the items in the list:</p><pre>/**<br> * A general interface for list items.<br> * This interface is used by {@link ListItemsVisibilityCalculator}<br> *<br> * @author danylo.volokh<br> */<br>public interface ListItem {<br>    /**<br>     * When this method is called, the implementation should provide a<br>     * visibility percents in range 0 - 100 %<br>     * @param view the view which visibility percent should be<br>     * calculated.<br>     * Note: visibility doesn&#39;t have to depend on the visibility of a<br>     * full view. <br>     * It might be calculated by calculating the visibility of any<br>     * inner View<br>     *<br>     * @return percents of visibility<br>     */<br>    int getVisibilityPercents(View view);<br><br>    /**<br>     * When view visibility become bigger than &quot;current active&quot; view<br>     * visibility then the new view becomes active.<br>     * This method is called<br>     */<br>    void setActive(View newActiveView, int newActiveViewPosition);<br><br>    /**<br>     * There might be a case when not only new view becomes active,<br>     * but also when no view is active.<br>     * When view should stop being active this method is called<br>     */<br>    void deactivate(View currentView, int position);<br>}</pre><p>The ListItemsVisibilityCalculator tracks the direction of scroll and calculate visibility of items in runtime. The item visibility might depend on any view inside single item in the list. It’s up to you to implement getVisibilityPercents() method.</p><p>There is a default implementation of this method in the sample demo app:</p><pre>/**<br> * This method calculates visibility percentage of currentView.<br> * This method works correctly when currentView is smaller then it&#39;s enclosure.<br> * @param currentView - view which visibility should be calculated<br> * @return currentView visibility percents<br> */<br>@Override<br><strong>public int </strong>getVisibilityPercents(View currentView) {<br><br>    <strong>int </strong>percents = 100;<br><br>    currentView.getLocalVisibleRect(mCurrentViewRect);<br><br>    <strong>int </strong>height = currentView.getHeight();<br><br>    <strong>if</strong>(viewIsPartiallyHiddenTop()){<br>        // view is partially hidden behind the top edge<br>    percents = (height - mCurrentViewRect.top) * 100 / height;</pre><pre>    } <strong>else if</strong>(viewIsPartiallyHiddenBottom(height)){</pre><pre>        percents = mCurrentViewRect.bottom * 100 / height;<br>    }<br><br>    <strong>return </strong>percents;<br>}</pre><p>So, each view needs to know how to calculate its visibility percents. SingleListViewItemActiveCalculator will be polling this value from each view when scroll is happening so the implementation should not be very heavy.</p><p>When visibility of any neighbor item exceeds the visibility of current active item the setActive method will be called. And when it is we should switch the playback.</p><p>There is also an ItemsPositionGetter that works as an adapter between ListItemsVisibilityCalculator and ListView or RecyclerView. This way ListItemsVisibilityCalculator doesn’t know if it’s ListView or RecyclerView. It just does its job. But it needs some information that is provided via ItemsPositionGetter:</p><pre>/**<br> * This class is an API for {@link ListItemsVisibilityCalculator}<br> * Using this class is can access all the data from RecyclerView / <br> * ListView<br> *<br> * There is two different implementations for ListView and for <br> * RecyclerView.<br> * RecyclerView introduced LayoutManager that&#39;s why some of data moved<br> * there<br> *<br> * Created by danylo.volokh on 9/20/2015.<br> */<br>public interface ItemsPositionGetter {<br> <br>   View getChildAt(int position);<br><br>    int indexOfChild(View view);<br><br>    int getChildCount();<br><br>    int getLastVisiblePosition();<br><br>    int getFirstVisiblePosition();<br>}</pre><p>Having that kind of logic in your model is messing up a bit with the idea of separating business logic from model. But with some modifications it might be isolated. And by the way it works fine even how it is now.</p><p>Here is the simple movie that shows how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Qqa81vAPYEzUWXq1dhfm6A.gif" /></figure><p>Here is a gradle dependency for the library:</p><pre>dependencies {<br>    compile &#39;com.github.danylovolokh:list-visibility-utils:0.2.0&#39;<br>}</pre><h4>Combination of Video Player Manager and List Visibility Utils to implement video playback in the scrolling list.</h4><p>Now we have two libraries that solves everything we need. Let’s combine them to get functionality we need.</p><p>Here the code from the fragment that uses RecyclerView:</p><ol><li>Initialize ListItemsVisibilityCalculator, and pass a reference to a list to it.</li></ol><pre>/**<br> * Only the one (most visible) view should be active (and playing).<br> * To calculate visibility of views we use {@link SingleListViewItemActiveCalculator}<br> */<br><strong>private final </strong>ListItemsVisibilityCalculator mVideoVisibilityCalculator = <strong>new </strong>SingleListViewItemActiveCalculator(<br><strong>new D</strong>efaultSingleItemCalculatorCallback(), mList);</pre><p>DefaultSingleItemCalculatorCallback just calls the ListItem.setActive method when active view changes, but you can override it by yourself and do whatever you need :</p><pre>/**<br> * Methods of this callback will be called when new active item is found {@link Callback#activateNewCurrentItem(ListItem, View, int)}<br> * or when there is no active item {@link Callback#deactivateCurrentItem(ListItem, View, int)} - this might happen when user scrolls really fast<br> */<br><strong>public interface </strong>Callback&lt;T <strong>extends </strong>ListItem&gt;{<br>    <strong>void </strong>activateNewCurrentItem(T item, View view, <strong>int </strong>position);<br>    <strong>void </strong>deactivateCurrentItem(T item, View view, <strong>int </strong>position);<br>}</pre><p>2. Initialize VideoPlayerManager.</p><pre>/**<br> * Here we use {@link SingleVideoPlayerManager}, which means that only one video playback is possible.<br> */<br><strong>private final </strong>VideoPlayerManager&lt;MetaData&gt; mVideoPlayerManager = <strong>new </strong>SingleVideoPlayerManager(<strong>new </strong>PlayerItemChangeListener() {<br>    @Override<br>    <strong>public void </strong>onPlayerItemChanged(MetaData metaData) {<br><br>    }<br>});</pre><p>3. Set on scroll listener to the RecyclerView and pass the scroll events to the list visibility utils.</p><pre>@Override<br><strong>public void </strong>onScrollStateChanged(RecyclerView view, <strong>int </strong>scrollState) {<br> mScrollState = scrollState;<br> i<strong>f</strong>(scrollState == RecyclerView.<em>SCROLL_STATE_IDLE </em>&amp;&amp; mList.isEmpty()){<br><br> mVideoVisibilityCalculator.onScrollStateIdle(<br>          mItemsPositionGetter,<br>          mLayoutManager.findFirstVisibleItemPosition(),<br>          mLayoutManager.findLastVisibleItemPosition());<br> }<br> }<br><br>@Override<br><strong>public void </strong>onScrolled(RecyclerView recyclerView, <strong>int </strong>dx, <strong>int </strong>dy) {<br> <strong>if</strong>(!mList.isEmpty()){<br>   mVideoVisibilityCalculator.onScroll(<br>         mItemsPositionGetter,<br>         mLayoutManager.findFirstVisibleItemPosition(),<br>         mLayoutManager.findLastVisibleItemPosition() -</pre><pre>         mLayoutManager.findFirstVisibleItemPosition() + 1,<br>         mScrollState);<br> }<br>}<br>});</pre><p>4. Create ItemsPositionGetter.</p><pre>ItemsPositionGetter mItemsPositionGetter = <br><strong>new </strong>RecyclerViewItemPositionGetter(mLayoutManager, mRecyclerView);</pre><p>5. And we call a method in onResume to start calculating the most visible item as soon as we open the screen.</p><pre>@Override<br><strong>public void </strong>onResume() {<br>    <strong>super</strong>.onResume();<br>    <strong>if</strong>(!mList.isEmpty()){<br>        // need to call this method from list view handler in order to have filled list<br><br>        mRecyclerView.post(<strong>new </strong>Runnable() {<br>            @Override<br>            <strong>public void </strong>run() {<br><br>                mVideoVisibilityCalculator.onScrollStateIdle(<br>                        mItemsPositionGetter,<br>                        mLayoutManager.findFirstVisibleItemPosition(),<br>                        mLayoutManager.findLastVisibleItemPosition());<br><br>            }<br>        });<br>    }<br>}</pre><p>And that’s it. We have a set of videos that are playing in the scrolled list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*6uK9qO4g5v3DralCH03yzA.gif" /></figure><p>Basically this is just the explanation of most important parts. There is a lot more code in the sample app here:</p><p><a href="https://github.com/danylovolokh/VideoPlayerManager">https://github.com/danylovolokh/VideoPlayerManager</a></p><p>Please see the source code for more details.</p><p>Cheers ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d04bc2148429" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/implementing-video-playback-in-a-scrolled-list-listview-recyclerview-d04bc2148429">Implementing video playback in a scrolled list (ListView &amp; RecyclerView)</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server polling and retrying failed operations. With Retrofit and RxJava.]]></title>
            <link>https://medium.com/android-development-by-danylo/server-polling-and-retrying-failed-operations-with-retrofit-and-rxjava-8bcc7e641a5a?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/8bcc7e641a5a</guid>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:29:41 GMT</pubDate>
            <atom:updated>2016-01-31T20:12:36.207Z</atom:updated>
            <content:encoded><![CDATA[<p>A very common case in developing rest application is server polling and retry. When server is doing some job and we need to ask (with some delay) if it’s finished, also when we got an error, sometimes we want to retry. I’ve decided to write about that after I stuck with implementing server polling correctly with RxJava. Eventually I got a good answer about it in <a href="http://stackoverflow.com/questions/34943734/using-of-skipwhile-combined-with-repeatwhen-in-rxjava-to-implement-server-po/34948978">this stackoverflow question.</a></p><p>In this article I will explain how easily we can do it with RxJava and Retrofit 1. I assume that you already know how to work with RxJava, Retrofit and how to set up application architecture with these great tools.</p><p>A few definitions that I will use in this article:</p><ul><li>“Predicate” — a class that is passed to some Observable methods, for Example: Observable.filter(/*here we pass the predicate*/), Observable.takeUntil(/*here we pass the predicate*/).</li><li>“Child of Observable” — an Observer that is chained after parents Observable. For example:</li></ul><pre>Observable<br>.filter(/*predicate here*/)<br>.takeUntil(/*predicate here*/)<br>.subscribe(/*subscriber here/)</pre><p>Observable returned from <strong>takeUntil() </strong>is a child of Observable returned by <strong>filter()</strong>, the Subscriber that is passed as a parameter to the <strong>subscribe()</strong> is a child of Observable returned from <strong>takeUntil()</strong>.</p><h4>Server Polling.</h4><p>This is the case when you are waiting for some job to be done by the server and you have to periodically make an API call to know if it’s already done.</p><p>Here is sample code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af5d84bfa88952cfc788bd48ce5e466f/href">https://medium.com/media/af5d84bfa88952cfc788bd48ce5e466f/href</a></iframe><p>It looks big, but it’s very easy to understand and it’s written with elegant chain of operators.</p><p>Assume that server returned <strong>“isJobDone=true”</strong> after third attempt, here is the log:</p><pre>repeatWhen, call<br>// at this stage the API call is performed<br>filter, call response isJobDone=false<br>takeUntil, call response isJobDone=false</pre><pre>// at this stage the API call is performed again<br>filter, call response isJobDone=false<br>takeUntil, call response isJobDone=false</pre><pre>// at this stage the API call is performed for the third time<br>filter, call response isJobDone=true<br>onNext response isJobDone=true<br>takeUntil, call response isJobDone=true<br>onCompleted</pre><p>In the next section I’ll explain why methods are called in that way.</p><h4>RxJava internals explained for server polling implementation.</h4><p>After the http request first of all the <strong>call()</strong> method of <strong>filter() </strong>predicate is called.</p><p>If we return “false” from <strong>filter()</strong> it means that result is not satisfying and we should not deliver it to the <strong>Subscriber&lt;ServerPollingResponse&gt;. </strong>Here we get the following chain of events:</p><ol><li>We returned “false”, it means that result was not delivered to the child of <strong>filter() </strong>aka<strong> Subscriber&lt;ServerPollingResponse&gt;.</strong></li><li>The call to <strong>onNext() </strong>was passed to <strong>takeUntil() </strong>Observable and <strong>call() </strong>method of its predicate was called.</li><li>We see that “job is not done yet” and we return “false” from <strong>call() </strong>method of <strong>takeUntil()</strong>.</li><li>It means that <strong>onNext() </strong>and<strong> onComplete() </strong>of <strong>repeatWhen() </strong>Observable will be called.</li><li>When<strong> onComplete()</strong> is called it causes a resubscribe to the original Observable with 5 seconds of delay. Basically this is causing http request to be called again. Which was our goal.</li></ol><p>If we return “true” from <strong>filter() </strong>it means that this result is satisfying and we get following chain of events:</p><ol><li>Result is delivered to <strong>onNext(ServerPollingResponse response)</strong> of filter’s child — the <strong>Subscriber&lt;ServerPollingResponse&gt;</strong>.</li><li>Then this result is delivered to <strong>call()</strong> method of <strong>takeUntil() </strong>predicate.</li><li>We also return “true” from <strong>takeUntil()</strong> because we got the “job done”.</li><li>Because we returned “true”, the <strong>takeUntil() </strong>operator<strong> </strong>calls <strong>onComplete() </strong>on its child. The child of <strong>takeUntil()</strong> is <strong>filter().</strong></li><li><strong>filter() </strong>calls the <strong>onComplete() </strong>of its child — which is the <strong>Subscriber&lt;ServerPollingResponse&gt;</strong>.</li><li><strong>takeUntil() </strong>unsubscribes immediately, that’s why Observable of <strong>repeatWhen() </strong>will not get a call to <strong>onNext() </strong>or <strong>onComplete() </strong>and the http request won’t be called again.</li></ol><p>The chain is terminated by internal <strong>unsubscribe() </strong>that is called from <strong>takeUntil() </strong>operator.</p><h4>Server polling with increasing the time of waiting on each repeat.</h4><p>The basic principle is the same. We just need to add a few chaining methods to the <strong>repeatWhen() </strong>predicate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22f8b10adedb767fcad2b5b4da0fe8ad/href">https://medium.com/media/22f8b10adedb767fcad2b5b4da0fe8ad/href</a></iframe><p>Here before each API call the original delay time is multiplied by the value of the attempt. Very simple and effective.</p><p>Here is the log:</p><pre>repeatWhen, call<br>// here is our first API call<br>filter, call response isJobDone=false<br>takeUntil, response isJobDone=false<br>zipWith, call, attempt 1<br>flatMap, call, repeatAttempt 1</pre><pre>// wait 10 seconds and run API call for the second time<br>filter, call response isJobDone=false<br>takeUntil, response isJobDone=false<br>zipWith, call, attempt 2<br>flatMap, call, repeatAttempt 2</pre><pre>// wait 20 seconds and run API call for the third time<br>filter, call response isJobDone=true<br>onNext response isJobDone=true<br>takeUntil, response isJobDone=true<br>onCompleted</pre><p>Please find the explanation below.</p><h4>RxJava zipWith() and flatMap() explained.</h4><p>I will omit those parts that were explained previously and jump right to the most relevant — <strong>zipWith()</strong> and <strong>flatMap().</strong></p><ol><li>After <strong>takeUntil() </strong>did it’s job the Observable returned from <strong>repeatWhen() </strong>starts its work. This Observable is a combined result of two functions: <strong>zipWith()</strong> and <strong>flatMap()</strong>.</li><li><strong>zipWith(parameter1, parameter2) </strong>take values emitted from Observable that came into <strong>repeatWhen()</strong> which is <strong>Void aVoid </strong>and value emitted by parameter1 aka<strong> Observable.range(COUNTER_START, ATTEMPTS) </strong>and passes it into function <strong>call(Void, Integer)</strong> method. In <strong>call()</strong> method we can do some stuff with these two parameters and return a value (In our case it’s Integer, but it can be anything, if we want something else we just need to change the third generic type in <strong>new Func2&lt;Void, Integer, /*change this*/Integer&gt;</strong>) but we just return the value we got from our Observable, this value is the repeat attempt.</li><li>The value from <strong>zipWith() </strong>is wrapped into Observable that emits this value. And we handle it in <strong>flatMap().</strong></li><li><strong>flatMap() </strong>takes the value and uses it to produce a timer Observable. Timer Observable waits for specified amount of time and passes control down the chain, to the original Observable that does the API call.</li></ol><p>We could omit using <strong>zipWith() </strong>and just use <strong>flatMap()</strong> inside the <strong>repeatWhen().</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/663c15b1493fe1a8d6c3bbb927a85614/href">https://medium.com/media/663c15b1493fe1a8d6c3bbb927a85614/href</a></iframe><p>In this case we would need to have a counter, control the attempt by ourselves and terminate the sequence when we have to stop. But we use <strong>zipWith()</strong> and RxJava does it for us!</p><h4>Retry when we got an error</h4><p>As you know in Retrofit 1 every network error is handled via <strong>onError()</strong> method.</p><p>To implement retry when we lost internet connection or get any http status besides 200 OK we have to use <strong>retryWhen() </strong>instead of <strong>repeatWhen(). </strong>And the parameters of <strong>zipWith() </strong>will be a bit different.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5addcd40a18b075b648cd6798d9013ba/href">https://medium.com/media/5addcd40a18b075b648cd6798d9013ba/href</a></iframe><p>The difference between <strong>repeatWhen()</strong> and <strong>retryWhen()</strong> is that <strong>repeatWhen()</strong> resubscribes when it gets <strong>onNext()</strong> and <strong>retryWhen()</strong> does that when is gets <strong>onError().</strong></p><h4>Lets combine repeatWhen() and retryWhen() to poll the server and retry if we failed.</h4><p>Here is the relevant code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80499dddf762a7ee085151083cc32b26/href">https://medium.com/media/80499dddf762a7ee085151083cc32b26/href</a></iframe><p>You may notice that I’ve wrapped the <strong>zipWith() </strong>and <strong>flatMap()</strong> into separate method and used compose to reuse it in <strong>repeatWhen() </strong>and <strong>retryWhen()</strong>. Now if we failed we retry, if we got success but “job is not ready yet” we will repeat.</p><p>RxJava rocks!</p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bcc7e641a5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/server-polling-and-retrying-failed-operations-with-retrofit-and-rxjava-8bcc7e641a5a">Server polling and retrying failed operations. With Retrofit and RxJava.</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing ImageView transition between activities for pre-Lollipop devices.]]></title>
            <link>https://medium.com/android-development-by-danylo/implementing-imageview-transition-between-activities-for-pre-lollipop-devices-8b24bc387a2a?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b24bc387a2a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:29:36 GMT</pubDate>
            <atom:updated>2016-03-22T22:45:33.144Z</atom:updated>
            <content:encoded><![CDATA[<p>In Android 5.0 Google introduced very fancy stuff called “Shared elements transition”. Using it we can do a very cool animation that makes it look like our UI elements are moving from one activity to another. Let’s try do it on an Android below 5.0. <strong>All the code from this article is on </strong><a href="https://github.com/danylovolokh/ImageTransition"><strong>GitHub.</strong></a></p><p>The animation is based on a known video from Chet Haase : <a href="https://www.youtube.com/watch?v=CPxkoe2MraA">DevBytes: Custom Activity Animations</a></p><p>The difference between what I will do here and the demo from Chet is that I will also animate the <strong>ImageView</strong> Matrix. This will make animation look more natural. The ImageView from previous screen can have <strong>ImageView.ScaleType</strong> different from the enlarged <strong>ImageView</strong> on the “next screen”. Here is a demo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*egJ-IU2Un4fBYOZNGrfFHw.gif" /><figcaption>Shared element transition from one activity to another.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*dTPkK-n4WXzqmcBYq8wwMg.gif" /><figcaption>Canceling of shared element transition until it’s finished.</figcaption></figure><p>Here is how it looks with a native shared element transition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*HsP9bLz2ZQWgb74axmTWkA.gif" /><figcaption>Shared element transition between activities on Android Lollipop.</figcaption></figure><h4>Making activity translucent.</h4><p>There is two activities :</p><ul><li><strong>ImagesListActivity.</strong></li><li><strong>ImageDetailsActivity.</strong></li></ul><p>First of all we have to make the content of <strong>ImagesListActivity</strong> visible while image transition animation is running. It is done by changing two attributes of activity style:</p><pre>&lt;item name=&quot;android:windowBackground&quot;&gt;<br>    @android:color/transparent<br>&lt;/item&gt;</pre><pre>&lt;item name=&quot;android:windowIsTranslucent&quot;&gt;<br>    true<br>&lt;/item&gt;</pre><p>Now <strong>ImageListActivity</strong> will be visible when <strong>ImageDetailsActivity</strong> is on the screen. It has one major drawback:</p><p>Eventually we make <strong>ImageDetailsActivity </strong>fully opaque by setting background color on the layout. The <strong>ImageListActivity</strong> will be still drawn by <strong>WindowManager</strong> even if it’s not visible!</p><p>So in our case we have two activities. In Android 5 they’ve managed to leave the “second Activity” translucent while animation is running and then make it fully opaque and after that the “first Activity” is not drawn anymore and can be easily garbage collected. So, sadly we don’t have that is versions below Lollipop.</p><p>Making <strong>ImageDetailsActivity </strong>translucent will also change the behaviour of <strong>ImagesListActivity. </strong>When <strong>ImageDetailsActivity</strong> is started only the <strong>onPause() </strong>callback will be called for <strong>ImagesListActivity.</strong></p><h4>Animate Entering ImageDetailsActivity.</h4><p>When image on <strong>ImagesListActivity</strong> is clicked <strong>ImageDetailsActivity</strong> is started:</p><pre>// ImagesListActivity</pre><pre>mImageDetailsImageModel = imageModel;</pre><pre>int[] screenLocation = new int[2];<br>image.getLocationInWindow(screenLocation);<br><br>Intent startIntent = ImageDetailsActivity.<em>getStartIntent</em>(this, <br>        imageFile,<br>        screenLocation[0],<br>        screenLocation[1],<br>        image.getWidth(),<br>        image.getHeight(),<br>        image.getScaleType());<br><br>startActivity(startIntent);</pre><p>Some data about clicked image has to be passed to the <strong>ImageDetailsActivity</strong>:</p><ul><li>Top-left position of clicked <strong>ImageView</strong>.</li><li>Width and height of clicked <strong>ImageView</strong>.</li><li><strong>ScaleType</strong> of clicked image.</li><li>Image file, to load the image in <strong>ImageDetailsActivity</strong>.</li></ul><p>Also the <strong>imageModel</strong> has to be saved in <strong>ImagesListActivity</strong> for further use.</p><p>In <strong>ImageDetailsActivity</strong> a copy of clicked <strong>ImageView</strong> is created and added to the root <strong>FrameLayout </strong>(android.R.id.content — the id of a root <strong>FrameLayout</strong> that is parent view for layout passed to <strong>setContentView()</strong> ):</p><pre>// ImageDetailsActivity</pre><pre>FrameLayout androidContent = (FrameLayout)<br>        getWindow()<br>        .getDecorView()<br>        .findViewById(android.R.id.<em>content</em>);</pre><pre>mTransitionImage = new ImageView(this);<br>androidContent.addView(mTransitionImage);<br><br>Bundle bundle = getIntent().getExtras();<br><br>int thumbnailTop = bundle.getInt(<em>KEY_THUMBNAIL_INIT_TOP_POSITION</em>)<br>        - getStatusBarHeight();<br>int thumbnailLeft = bundle.getInt(<em>KEY_THUMBNAIL_INIT_LEFT_POSITION</em>);<br>int thumbnailWidth = bundle.getInt(<em>KEY_THUMBNAIL_INIT_WIDTH</em>);<br><br>int thumbnailHeight = bundle.getInt(<em>KEY_THUMBNAIL_INIT_HEIGHT</em>);<br><br>ImageView.ScaleType scaleType = (ImageView.ScaleType) <br>        bundle.getSerializable(<em>KEY_SCALE_TYPE</em>);<br><br>FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) <br>        mTransitionImage.getLayoutParams();</pre><pre>layoutParams.height = thumbnailHeight;<br>layoutParams.width = thumbnailWidth;<br>layoutParams.setMargins(thumbnailLeft, thumbnailTop, 0, 0);<br><br>File imageFile = (File)      <br>        getIntent()<br>        .getSerializableExtra(<em>IMAGE_FILE_KEY</em>);</pre><pre>mTransitionImage.setScaleType(scaleType);<br><br>mImageDownloader.load(imageFile).noFade().into(mTransitionImage);</pre><p>We set initial margins to the view so that it was situated at exact same spot that view from the previous screen was.</p><p>You may have noticed <strong>mImageDownloader. </strong>I use Picasso in this project to load images.</p><p>Also the enlarged version of ImageView has to be loaded to the layout. And only after that we can start running entering animation:</p><pre>// ImageDetailsActivity</pre><pre>mImageDownloader.load(imageFile).into(mEnlargedImage, new Callback() {<br><br>       <strong> /**<br>         * Image is loaded when this method is called<br>         */</strong><br>        @Override<br>        public void onSuccess() {<br>            Log.<em>v</em>(<em>TAG</em>, &quot;onSuccess, mEnlargedImage&quot;);<br><strong><br>            // In this callback we already have image set into <br>            // ImageView and we can use it&#39;s Matrix for animation<br>            // But we have to wait for final measurements. We use <br>            // OnPreDrawListener to be sure everything is measured</strong><br><br>            if (savedInstanceState == null) {<br>            <br><strong>            // if savedInstanceState is null activity is started for</strong></pre><pre><strong>            // the first time.<br>            // run the animation</strong></pre><pre>                runEnteringAnimation();</pre><pre>            } else {</pre><pre>            <strong>// activity was retrieved from recent apps. No <br>            // animation needed, just load the image</strong></pre><pre>            }<br>        }<br><br>        @Override<br>        public void onError() {</pre><pre>            <strong>// CAUTION: on error is not handled. If OutOfMemory <br>            // occured during image loading we have to handle it <br>            // here</strong></pre><pre>            Log.<em>v</em>(<em>TAG</em>, &quot;onError, mEnlargedImage&quot;);<br>        }<br>    });<br>}</pre><p>The important is that if <strong>savedInstanceState </strong>is null only then we have to run the animation. If it’s not — it was probably retrieved from recent apps or opened after returning from other activity.</p><h4>Using OnPreDrawListener to start the animation at the correct time.</h4><p>Here is a code from <strong>runEnteringAnimation()</strong> method.</p><p>This method does very tricky part:<br>It sets up {<strong>@link android.view.ViewTreeObserver.OnPreDrawListener</strong>}. When <strong>onPreDraw() </strong>method is called the layout is already measured. It means that we can use locations of images on the screen at this point. Here is what we have to do in <strong>OnPreDrawListener:</strong></p><ol><li>When first frame is drawn we start animation.</li><li>We just let second frame to be drawn.</li><li>Make the <strong>ImageView</strong> that was clicked on the previous screen invisible and remove <strong>onPreDrawListener. </strong>We make it invisible to make it look like copied <strong>ImageView</strong> that is on <strong>ImageDetailsActivity</strong> look like it was moved from the place where clicked image was. And when it’s moved from there it has to leave an empty space.</li></ol><pre>// ImageDetailsActivity</pre><pre>private void runEnteringAnimation() {<br>    Log.<em>v</em>(<em>TAG</em>, &quot;runEnteringAnimation, addOnPreDrawListener&quot;);<br><br>    mEnlargedImage<br>        .getViewTreeObserver()<br>        .addOnPreDrawListener(<br>        new ViewTreeObserver.OnPreDrawListener() {<br><br>        int mFrames = 0;<br><br>        @Override<br>        public boolean onPreDraw() {<br>            <br>            <strong>// When this method is called we already have everything <br>            // laid out and measured so we can start our animation</strong><br>            <br>            Log.<em>v</em>(<em>TAG</em>, &quot;onPreDraw, mFrames &quot; + mFrames);<br><br>            switch (mFrames++) {<br>                case 0:<br>                    <strong>/**<br>                     * 1. start animation on first frame<br>                     */<br>       <br>       </strong>final int[] finalLocationOnTheScreen = new int[2];<br>       mEnlargedImage.getLocationOnScreen(finalLocationOnTheScreen);<br><br>       mEnterScreenAnimations.playEnteringAnimation(<br>                            finalLocationOnTheScreen[0], // left<br>                            finalLocationOnTheScreen[1], // top<br>                            mEnlargedImage.getWidth(),<br>                            mEnlargedImage.getHeight());<br><br>                    return true;<br>                case 1:<br>                    <strong>/**<br>                     * 2. Do nothing. We just draw this frame<br>                     */</strong><br><br>                    return true;<br>            }<br>            <strong>/**<br>             * 3.<br>             * Make view on previous screen invisible on after this <br>             * drawing frame<br>             * Here we ensure that animated view will be visible <br>             * when we make the viw behind invisible<br>             */</strong><br>            Log.<em>v</em>(<em>TAG</em>, &quot;run, onAnimationStart&quot;);<br>            mBus.post(new ChangeImageThumbnailVisibility(false));<br>            mEnlargedImage.getViewTreeObserver()<br>            .removeOnPreDrawListener(this);<br><br>            Log.<em>v</em>(<em>TAG</em>, &quot;onPreDraw, &lt;&lt; mFrames &quot; + mFrames);<br><br>            return true;<br>        }<br>    });<br>}</pre><p>Why do we handle frames in this way:</p><p>The Android rendering system is double-buffered and we have to let system draw two frames to be sure that <strong>ImageView</strong> that is transitioned is already visible. Similar technique is used in the SDK. If we don’t do that the <strong>ImageView</strong> might blink when animation starts.</p><p>See here : <strong>android.app.EnterTransitionCoordinator#startSharedElementTransition</strong><br>You can read more about it at this link: <a href="https://source.android.com/devices/graphics/architecture.html">https://source.android.com/devices/graphics/architecture.html</a></p><p>In the code above the is a call from Otto event bus:</p><pre>mBus.post(new ChangeImageThumbnailVisibility(false));</pre><p>It sends a message to <strong>ImagesListActivity</strong> in order to hide clicked image in the images list. Here is how it’s done:</p><pre>// ImagesListActivity</pre><pre>@Subscribe<br>public void hideImageThumbnail(ChangeImageThumbnailVisibility message){<br>    Log.<em>v</em>(<em>TAG</em>, &quot;&gt;&gt; hideImageThumbnail&quot;);<br><br>    mImageDetailsImageModel.setVisibility(message.isVisible());<br><br>    updateModel(mImageDetailsImageModel);<br><br>    Log.<em>v</em>(<em>TAG</em>, &quot;&lt;&lt; hideImageThumbnail&quot;);<br>}</pre><pre><strong>/**<br> * This method basically changes visibility of concrete item<br> */</strong><br>private void updateModel(Image imageToUpdate) {<br>    Log.<em>v</em>(<em>TAG</em>, &quot;updateModel, imageToUpdate &quot; + imageToUpdate);<br>    for (Image image : mImagesList) {<br><br>        if(image.equals(imageToUpdate)){<br>            image.setVisibility(imageToUpdate.isVisible());<br>            break;<br>        }<br>    }<br>    int index = mImagesList.indexOf(imageToUpdate);<br>    Log.<em>v</em>(<em>TAG</em>, &quot;updateModel, index &quot; + index);<br><br>    mAdapter.notifyItemChanged(index);<br><br>    <strong>/**<br>     * For some reason recycler view is not always redrawn when <br>     * adapter is updated.<br>     * onBindViewHolder is called but image doesn&#39;t disappear from <br>     * screen. That&#39;s why we have to do this invalidation<br>     */</strong><br>    Rect dirty = new Rect();<br>    View viewAtPosition = mLayoutManager.findViewByPosition(index);<br>    viewAtPosition.getDrawingRect(dirty);<br>    mRecyclerView.invalidate(dirty);<br>}</pre><p>You can see that here we use <strong>mImageDetailsImageModel </strong>that was saved when <strong>ImageDetailsActivity</strong> was launched.</p><h4>Creating the actual animation.</h4><p>Let’s have a closer look to this method : <strong>playEnteringAnimation</strong>.</p><pre>public void playEnteringAnimation(<br>    int left, <br>    int top, <br>    int width,  <br>    int height) {</pre><pre>    Log.<em>v</em>(<em>TAG</em>, &quot;&gt;&gt; playEnteringAnimation&quot;);<br><br>    mToLeft = left;<br>    mToTop = top;<br>    mToWidth = width;<br>    mToHeight =  height;<br><br>    AnimatorSet imageAnimatorSet = createEnteringImageAnimation();<br><br>    Animator mainContainerFadeAnimator = <br>        createEnteringFadeAnimator();<br><br>    mEnteringAnimation = new AnimatorSet();<br>    mEnteringAnimation.setDuration(<em>IMAGE_TRANSLATION_DURATION</em>);<br>    mEnteringAnimation.setInterpolator(<br>        new AccelerateInterpolator());</pre><pre>    mEnteringAnimation.addListener(new SimpleAnimationListener() {<br><br>        @Override<br>        public void onAnimationCancel(Animator animation) {<br>            mEnteringAnimation = null;<br>        }<br><br>        @Override<br>        public void onAnimationEnd(Animator animation) {<br><br>            if (mEnteringAnimation != null) {<br>                mEnteringAnimation = null;<br><br>                mImageTo.setVisibility(View.<em>VISIBLE</em>);<br>                mAnimatedImage.setVisibility(View.<em>INVISIBLE</em>);<br>            } else {<br>               <strong> // Animation was cancelled. Do nothing</strong><br>            }<br>        }<br>    });<br><br>    mEnteringAnimation.playTogether(<br>            imageAnimatorSet,<br>            mainContainerFadeAnimator<br>    );<br><br>    mEnteringAnimation.start();<br>    Log.<em>v</em>(<em>TAG</em>, &quot;&lt;&lt; playEnteringAnimation&quot;);<br>}</pre><p>This method does few things:</p><ol><li>It combines 2 animations: “Image entering animation” and “Main container fade in animation”</li><li>If entering animation was not cancelled and animation is finished it sets “animated image” to state “INVISIBLE” and “Enlarged image” to “VISIBLE”.</li></ol><p>Method <strong>createEnteringFadeAnimator()</strong> is very simple. It’s a usual ObjectAnimator for animating background:</p><pre>private ObjectAnimator createEnteringFadeAnimator() {<br>    return <br>        ObjectAnimator.<em>ofFloat</em>(mMainContainer, &quot;alpha&quot;, 0.0f, 1.0f);<br>}</pre><h4>Animating image position and ImageView Matrix.</h4><p>The fun comes if we look at <strong>createEnteringImageAnimation() </strong>from previous paragraph.</p><pre>private AnimatorSet createEnteringImageAnimation() {<br>    Log.<em>v</em>(<em>TAG</em>, &quot;&gt;&gt; createEnteringImageAnimation&quot;);<br>    <br>    ObjectAnimator positionAnimator = <br>        createEnteringImagePositionAnimator();<br>    <br>    ObjectAnimator matrixAnimator = <br>        createEnteringImageMatrixAnimator();<br><br>    AnimatorSet enteringImageAnimation = new AnimatorSet();<br>    <br>    enteringImageAnimation<br>        .playTogether(positionAnimator, matrixAnimator);<br><br>    Log.<em>v</em>(<em>TAG</em>, &quot;&lt;&lt; createEnteringImageAnimation&quot;);<br>    return enteringImageAnimation;<br>}</pre><p>This method combines 2 animations and return <strong>AnimatorSet.</strong></p><p>Method <strong>createEnteringImagePositionAnimator() </strong>creates animator that animates image transition on the screen from the place where image on previous screen was to the place where it should be on <strong>ImageDetailsActivity</strong> screen.</p><pre>private ObjectAnimator createEnteringImagePositionAnimator() {<br><br>    Log.<em>v</em>(<em>TAG</em>, &quot;createEnteringImagePositionAnimator&quot;);<br><br>    PropertyValuesHolder propertyLeft = PropertyValuesHolder.<em>ofInt</em>(<br>            &quot;left&quot;, <br>            mAnimatedImage.getLeft(), <br>            mToLeft);</pre><pre>    PropertyValuesHolder propertyTop = PropertyValuesHolder.<em>ofInt</em>(<br>            &quot;top&quot;, <br>            mAnimatedImage.getTop(),<br>            mToTop - getStatusBarHeight());<br><br>    PropertyValuesHolder propertyRight = PropertyValuesHolder.<em>ofInt</em>(<br>            &quot;right&quot;, <br>            mAnimatedImage.getRight(), <br>            mToLeft + mToWidth);</pre><pre>   PropertyValuesHolder propertyBottom = PropertyValuesHolder.<em>ofInt</em>(<br>            &quot;bottom&quot;, <br>            mAnimatedImage.getBottom(), <br>            mToTop + mToHeight - getStatusBarHeight());<br><br>   ObjectAnimator animator = ObjectAnimator.<em>ofPropertyValuesHolder</em>(<br>            mAnimatedImage, <br>            propertyLeft, <br>            propertyTop, <br>            propertyRight, <br>            propertyBottom);</pre><pre>   animator.addListener(new SimpleAnimationListener() {<br>        @Override<br>        public void onAnimationEnd(Animator animation) {<br>            <strong>// set new parameters of animated ImageView. This will <br>            // prevent blinking of view when set visibility to <br>            // visible in Exit animation</strong><br>            <br>            FrameLayout.LayoutParams layoutParams = <br>                  (FrameLayout.LayoutParams) mAnimatedImage<br>                                         .getLayoutParams();</pre><pre>            layoutParams.height = mImageTo.getHeight();<br>            layoutParams.width = mImageTo.getWidth();<br>            <br>            layoutParams.setMargins(<br>                mToLeft, <br>                mToTop - getStatusBarHeight(), <br>                0, <br>                0);<br>        }<br>    });<br>    return animator;<br>}</pre><p>So, the method creates an <strong>ObjectAnimator</strong> that animates <strong>View</strong> properties:</p><ol><li>“left” will animate <strong>ImageView</strong> position over the X axis.</li><li>“top” will animate <strong>ImageView</strong> position over the Y axis. You may notice that final top position subtracts the height of status bar. That’s because the value of <strong>mToTop </strong>doesn’t takes into account the height of status bar. It’s a top position on the screen.</li><li>“bottom” together with “top” will basically animate <strong>ImageView</strong> height. Status bar height is also subtracted from <strong>mToHeight</strong>.</li><li>“right” together with “left” causes <strong>ImageView</strong> width to change.</li></ol><p>When animation ends it fixes the position of the image by setting margins to the <strong>ImageView</strong> layout params.</p><h4>Animating ImageView Matrix.</h4><p>To animate <strong>ImageView</strong> Matrix transform we need to call a method <strong>ImageView.animateTransform(). </strong>But this method is invisible for developers. So we will create custom property:</p><pre><strong>/**<br> * This property is passed to ObjectAnimator when we are animating<br> * image matrix of ImageView<br> */</strong><br>Property&lt;ImageView, Matrix&gt; <em>ANIMATED_TRANSFORM_PROPERTY <br></em>= new Property&lt;ImageView, Matrix&gt;(Matrix.class, &quot;animatedTransform&quot;){</pre><pre>    <strong>/**<br>     * This is copy-paste form ImageView#animateTransform - method<br>     * is invisible in sdk<br>     */</strong><br>    @Override<br>    public void set(ImageView imageView, Matrix matrix) {<br>        Drawable drawable = imageView.getDrawable();<br>        if (drawable == null) {<br>            return;<br>        }<br>        if (matrix == null) {</pre><pre>            drawable.setBounds(<br>            0, <br>            0, <br>            imageView.getWidth(), <br>            imageView.getHeight());</pre><pre>        } else {</pre><pre>            drawable.setBounds(<br>            0, <br>            0, <br>            drawable.getIntrinsicWidth(),<br>            drawable.getIntrinsicHeight());<br>           <br>            Matrix drawMatrix = imageView.getImageMatrix();<br>            <br>            if (drawMatrix == null) {<br>                drawMatrix = new Matrix();<br>                imageView.setImageMatrix(drawMatrix);<br>            }</pre><pre>            imageView.setImageMatrix(matrix);<br>        }<br>        imageView.invalidate();<br>    }</pre><pre>    @Override<br>    public Matrix get(ImageView object) {<br>        return null;<br>    }<br>};</pre><p>This custom property is basically a copy-paste from <strong>ImageView#animateTransform</strong>. What it does is that when <strong>Animator</strong> will try to animate property of <strong>animatedTransform</strong> the <strong>set(ImageView, Matrix)</strong> method will be called. And this method sets new <strong>Matrix</strong> to the <strong>ImageView</strong> and calls <strong>invalidate()</strong> so that <strong>ImageView</strong> will be redrawn.</p><p>Also, to “know” how <strong>ImageView</strong> <strong>Matrix</strong> should be changed during animation we need to have so called <strong>MatrixEvaluator</strong>:</p><pre><strong>/**<br> * This class is passed to ObjectAnimator in order to animate<br> * changes in ImageView image matrix<br> */</strong><br>public class MatrixEvaluator implements TypeEvaluator&lt;Matrix&gt; {</pre><pre>    float[] mTempStartValues = new float[9];<br>    float[] mTempEndValues = new float[9];</pre><pre>    Matrix mTempMatrix = new Matrix();</pre><pre>    @Override<br>    public Matrix evaluate(float fraction, <br>                           Matrix startValue, <br>                           Matrix endValue) {</pre><pre>        startValue.getValues(mTempStartValues);<br>        endValue.getValues(mTempEndValues);<br>        <br>        for (int i = 0; i &lt; 9; i++) {</pre><pre>            float diff = mTempEndValues[i] - mTempStartValues[i];<br>            mTempEndValues[i] = <br>                   mTempStartValues[i] <br>                   + (fraction * diff);<br>        }<br>        mTempMatrix.setValues(mTempEndValues);</pre><pre>        return mTempMatrix;<br>    }<br>}</pre><p>This class (<strong>MatrixEvaluator</strong>) together with <strong><em>ANIMATED_TRANSFORM_PROPERTY</em></strong><em> </em>are<em> </em>passed to the ObjectAnimator. To animate <strong>ImageView</strong> <strong>Matrix</strong>.</p><p>There is this method called <strong>createEnteringImageMatrixAnimator()</strong>. It is responsible for creating ObjectAnimator that animates <strong>ImageView</strong> <strong>Matrix.</strong></p><pre>private ObjectAnimator createEnteringImageMatrixAnimator() {<br><br>    Matrix initMatrix = MatrixUtils.<em>getImageMatrix</em>(mAnimatedImage);<br>    <strong>// store the data about original matrix into array.<br>    // this array will be used later for exit animation</strong><br>    initMatrix.getValues(mInitThumbnailMatrixValues);<br><br>    final Matrix endMatrix = MatrixUtils.<em>getImageMatrix</em>(mImageTo);<br><br>    mAnimatedImage.setScaleType(ImageView.ScaleType.<em>MATRIX</em>);<br><br>    return ObjectAnimator.<em>ofObject</em>(<br>        mAnimatedImage, <br>        MatrixEvaluator.<em>ANIMATED_TRANSFORM_PROPERTY</em>,<br>        new MatrixEvaluator(), initMatrix, endMatrix);<br>}</pre><p>This method also saves the values of initial <strong>Matrix</strong> so that these values could be used when creating “Exit animation”</p><p>Also there is one very important thing: the animated <strong>ImageView</strong> Scale type has to be set to <strong>ScaleType.Matrix</strong>.</p><h4>Animate Exiting ImageDetailsActivity.</h4><p>There is nothing special about animating exit from the screen. Basically we run the same animation in the reverse. The only thing that we really need to handle is that animate exiting if entering animation is in the middle. We have to stop entering animation (<strong>ImageView</strong> view transition should also stop somewhere in the middle of it’s path) and then animate ImageView back to it’s initial position.</p><p>We also have to handle pressing “back” button.</p><pre>@Override<br>public void onBackPressed() {<br>   <strong> //We don&#39;t call super to keep this activity on the screen when <br>    //back is pressed</strong><br>    Log.<em>v</em>(<em>TAG</em>, &quot;onBackPressed&quot;);<br><br>    mEnterScreenAnimations.cancelRunningAnimations();<br><br>    Bundle initialBundle = getIntent().getExtras();<br>    int toTop = <br>        initialBundle.getInt(<em>KEY_THUMBNAIL_INIT_TOP_POSITION</em>);<br>    int toLeft = <br>        initialBundle.getInt(<em>KEY_THUMBNAIL_INIT_LEFT_POSITION</em>);<br>    int toWidth = <br>        initialBundle.getInt(<em>KEY_THUMBNAIL_INIT_WIDTH</em>);<br>    int toHeight = <br>        initialBundle.getInt(<em>KEY_THUMBNAIL_INIT_HEIGHT</em>);<br><br>    mExitScreenAnimations.playExitAnimations(<br>        toTop,<br>        toLeft,<br>        toWidth,<br>        toHeight,<br>        mEnterScreenAnimations.getInitialThumbnailMatrixValues());<br>    }</pre><p>Here is the flow:</p><ol><li>We cancel “entering” animation if it’s still running. “Entering” animation is designed in the way that it will leave animated <strong>ImageView </strong>at exact same spot where it was during transition when animation was cancelled.</li><li>We retrieve <strong>ImageView</strong> initial properties from the bundle that was passed from <strong>ImagesListActivity. </strong>These values now are passed to the <strong>ExitScreenAnimations</strong> class that will use them as final properties when running “exiting” animation.</li><li>It gets initial values of <strong>ImageView</strong> <strong>Matrix</strong> that were stored when “entering” animation was created.</li></ol><p>There is almost no difference between “entering” and “exiting” animation. Please have a look at the source code on the <a href="https://github.com/danylovolokh/ImageTransition">Github</a> for more details.</p><p>That’s it.</p><p>Cheers ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b24bc387a2a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/implementing-imageview-transition-between-activities-for-pre-lollipop-devices-8b24bc387a2a">Implementing ImageView transition between activities for pre-Lollipop devices.</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exhaustive list of Android SDK methods that require Runtime Permission Check.]]></title>
            <link>https://medium.com/android-development-by-danylo/exhaustive-list-of-android-sdk-methods-that-require-runtime-permission-check-a08ff8e88832?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/a08ff8e88832</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[runtime-permissions]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:29:12 GMT</pubDate>
            <atom:updated>2016-06-12T16:48:43.197Z</atom:updated>
            <content:encoded><![CDATA[<h4>The problem</h4><p>We’ve recently added support of <a href="https://developer.android.com/training/permissions/requesting.html">Runtime Permissions</a>. Some of the places where we had to handle them were shown by lint, but not everything is shown by lint. For example, calling <strong>Camera.open() </strong>also causes SecurityException if user haven’t granted Camera Permission, and lint didn’t show us this “dangerous” method.</p><p>Going through whole 200K lines of code and searching for places where we could crash with SecurityException became real pain.</p><h4>Permissions Reference</h4><p>We had an idea that it would be great if Google would give us exhaustive list of methods which require requesting permission from user, but that didn’t happen.</p><p>We thought that other developers probably also face this problem when implementing <a href="https://developer.android.com/training/permissions/requesting.html">Runtime Permission.</a> So we decided to create the list ourselves:</p><p><a href="https://github.com/danylovolokh/PermissionsReference"><strong>PermissionsReferenc</strong></a><strong>e</strong> — its a project with which we (Android developers) can make our life easier.</p><p>Currently it doesn’t contains a list of all methods which require Runtime Permission check, so the list is not exhaustive. Yet. But we believe that with help of other developers we can fulfil the list very fast.</p><p>Project also contains a sample application that demonstrates how Runtime Permission check works with every specific method. You can choose two options:</p><ul><li>Crash — the application will call “dangerous” method without asking the permission. It will lead to SecurityException.</li><li>Ask Permission — the application will do the Runtime Permission check before calling “dangerous” method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X6OxEUHk9GYlT3aR5rISXA.png" /></figure><p>Let make our life better. We encourage everyone to contribute to the project.</p><p><a href="https://github.com/danylovolokh/PermissionsReference"><strong>PermissionsReference</strong></a></p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a08ff8e88832" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/exhaustive-list-of-android-sdk-methods-that-require-runtime-permission-check-a08ff8e88832">Exhaustive list of Android SDK methods that require Runtime Permission Check.</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android 16]]></title>
            <link>https://medium.com/android-development-by-danylo/android-16-e56c27173ef4?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/e56c27173ef4</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:24:29 GMT</pubDate>
            <atom:updated>2016-10-07T09:22:05.034Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will cover 16 things that I’ve learned during last few years of developing Android applications. I’d like to cover all 100500 things I’ve learned but I want to start from 16.</p><p>BTW: <a href="http://dragonball.wikia.com/wiki/Android_16">If you know what the name of the guy on the picture below it means we share a common interest about Android and anime.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4bEPbqFz2gCnpgpi9emag.jpeg" /></figure><ol><li>Care about Turkish locale.</li><li>Add enum values to the end of enum.</li><li>Max size of Bitmap that can be set to ImageView is 4096*4096 px.</li><li>Typeface.createFromAsset is leaking memory.</li><li>MAT is perfect for finding memory leaks.</li><li>Wrong usage of event bus can really bring a lot of problems.</li><li>Multiprocess sucks in so many ways.</li><li>Doze mode and MediaCodec.</li><li>Use a wrapper for the Log class.</li><li>RxJava can be great replacement for AsyncTask.</li><li>Test your code with “Do not keep activities”.</li><li>About code convention.</li><li>Care about creating objects.</li><li>Use Fabric for analytics.</li><li>Hungarian notation is useful for reading patches.</li><li>QA team are your friends.</li></ol><h3>Care about Turkish Locale.</h3><p>Turkish language has <a href="https://en.wikipedia.org/wiki/Dotted_and_dotless_I">Dotted and dotless I</a>. What does it mean for us?</p><p>We know that #perfmatters and in Android we <a href="https://www.youtube.com/watch?v=Hzs6OBcvNQE">shouldn’t use enums</a> but we still have enums in our applications. And one of the most not obvious bugs happened to us when we were mapping fields from server response to enum values, for example:</p><pre>enum Surname {</pre><pre>    <em>MORNINGSTAR</em>, U<em>NDERWOOD</em></pre><pre>}</pre><p>When the we are trying to map String to appropriate enum value we should care about locale.</p><p><em>In English locale:</em></p><pre>String strSurname = &quot;Morningstar&quot;;<br>Surname surname = Surname.<em>valueOf</em>(strSurname.toUpperCase());</pre><p>Result — Works fine.</p><p><em>In Turkish Turkish locale:</em></p><pre>String strSurname = &quot;Morningstar&quot;;<br>Surname surname = Surname.<em>valueOf</em>(strSurname.toUpperCase());</pre><p>Result — Crash.</p><pre>Caused by: java.lang.IllegalArgumentException: MORNİNGSTAR is not a constant in com.myapp.MainActivity$Surname</pre><p><strong><em>The solution:</em></strong></p><pre>String strSurname = &quot;Morningstar&quot;;<br>Surname surname = Surname.<em>valueOf</em>(<br>                  strSurname.toUpperCase(Locale.<em>ENGLISH</em>)<br>);</pre><p>When we faced this problem for the second time we enabled lint option in build.gradle which will stop the build if we didn’t handle the case.</p><pre>lintOptions {<br>    checkReleaseBuilds true<br>    abortOnError true<br>    enable &#39;DefaultLocale&#39;<br>    check &#39;DefaultLocale&#39;<br>    error &#39;DefaultLocale&#39;<br>}</pre><p>More about ‘DefaultLocale’ can be read <a href="http://tools.android.com/tips/lint-checks">here.</a></p><h3>Add enum values to the end of enum.</h3><p>Very often enum values are stored in the application by it’s ordinal number.</p><p>If <em>surnameNumber</em> will be stored somewhere in persistent memory and you will add a new enum value and put it into position before stored ordinal then after update of your application you will fail to restore the correct enum.</p><p>Use case:</p><ol><li>Assume you have this peace of code somewhere in your app.</li></ol><pre>enum Surname {</pre><pre><em>MORNINGSTAR</em>, U<em>NDERWOOD</em></pre><pre>}</pre><pre>Surname surname = Surname.<em>MORNINGSTAR</em>;<br>int surnameNumber = surname.ordinal(); // value = 0</pre><pre>// store surname into persistent storage.</pre><p>2. Add new enum value to the front of your values.</p><pre>enum Surname {</pre><pre><strong>TARGARYEN</strong>, <em>MORNINGSTAR</em>, U<em>NDERWOOD</em></pre><pre>}</pre><p>3. Release this version of the enum to your users. Let them update your application.</p><p>4. Check the place where you retrieve stored <em>surnameNumber.</em></p><pre>// get a value from storage. value = 0 - &gt; should be &quot;MORNINGSTAR&quot;<br>int storedSurnameNumber = //...</pre><pre>// create actual enum. <br>Surname surname = Surname.<em>values</em>()[storedSurnameNumber];</pre><pre><em>/**<br> * Actual : surname = TARGARYEN<br> * Expected : surname = MORNINGSTAR<br> */</em></pre><p>We’ve almost introduced a critical bug with this mistake. QA team saved us before releasing it.</p><h3>Max size of Bitmap that can be set to ImageView is 4096*4096 px.</h3><p>For the last three years I have been working with bitmaps and there is one important peculiarity of ImageView. There is few good justifications of why do we have to scale bitmaps before setting them to ImageView. The main reason for it is that we we scale bitmaps we consume less memory. But there is also one restriction:</p><pre>W/OpenGLRenderer(10630): Bitmap too large to be uploaded into a texture (4400x640, max=4096x4096)</pre><p>We cannot set an image to the Image view if we exceeded max size. That’s why it is good to use tools for image processing, they are handle the scaling for you:</p><ul><li><a href="http://square.github.io/picasso/">Picasso</a></li><li><a href="https://github.com/bumptech/glide">Glide</a></li></ul><h3>Typeface.createFromAsset is leaking memory.</h3><p>All of us uses <em>Typeface.createFromAsset()</em> to set a custom font in our TextViews. But not everyone knows that it loads font to the memory and this memory is never released.</p><pre>Typeface t= Typeface.<em>createFromAsset</em>(mContext.getAssets(), fontPath); <br>textView.setTypeface(t);</pre><p>If you use this code in your every TextView you will leak memory as many times as you will use it.</p><p>To see this you need to look into Android Memory info file. It can be created by pressing “Memory Usage” in your Android Studio monitor.</p><blockquote>Asset Allocations<br> zip:/data/app/com.myappp.apk:/assets/fonts/Value-Medium.otf: 127K<br> zip:/data/app/com.myappp.apk:/assets/fonts/Value-Regular.otf: 127K<br> zip:/data/app/com.myappp.apk:/assets/fonts/Value-Bold.otf: 128K</blockquote><blockquote>….</blockquote><p>There is also a <a href="https://code.google.com/p/android/issues/detail?id=9904">bug reported here.</a></p><p><strong><em>The solution:</em></strong></p><p>You need to create a simple cache that loads font only once and then shares this object with all the TextViews which font has to be changed.</p><pre>class FontCache { // it needs to be Singleton</pre><pre>private final Hashtable&lt;String, Typeface&gt; mCache = new Hashtable&lt;&gt;();</pre><pre>public Typeface get(String fontPath) {<br>    if (!mCache.containsKey(fontPath)) {<br>        Typeface t = Typeface<br>                .<em>createFromAsset</em>(mContext.getAssets(), fontPath);<br>        mCache.put(fontPath, t);<br>    }<br>    return mCache.get(fontPath);<br>}</pre><pre>}</pre><h3>MAT is perfect for finding memory leaks.</h3><p>Eclipse memory analyzer (MAT) — one of my favourite tools. Every time I have to deal with memory leaks — it’s the tool I use. Usage is very simple. The best guide for it was published back in 2011.</p><p><a href="https://www.youtube.com/watch?v=_CruQY55HOk">Google I/O 2011: Memory management for Android Apps</a></p><p>In simple terms:</p><ol><li>You reproduce a memory leak.</li><li>Manually turn on Garbage collector to clean all the garbage.</li><li>Collect heap information from Android Studio via “Dump Java heap for selected client”.</li><li>Convert dump file to a file type that can be recognized by MAT via tool that is called “hprof-conv” which is located here: “android_sdk\platform-tools\”</li><li>Open the converted file in MAT and use dominator three to find objects that shouldn’t be there.</li></ol><p>Here is also a short video provided by Colt:</p><p><a href="https://www.youtube.com/watch?v=h7qHsk1nWKI">Android Performance Patterns: Performance Cost of Memory Leaks</a></p><h3>Wrong usage of event bus can really bring a lot of problems.</h3><p>I’ve recently fixed a bug where we were registering/unregistering a Fragment to the EventBus not only in <em>onStart() </em>/ <em>onStop() </em>and also registering it in <em>onActivityResult() </em>because of some race conditions. And I’ve found a memory leak that after <em>onActivityResult()</em> we never unregister the EventBus and it holds a reference to the Fragment forever.</p><p>EventBus very often causes a lot of problems with comparison of how many problems it solves because:</p><ol><li>It’s not an OOP approach. You don’t have direct callbacks and in some cases using EventBus looks like sending a message and hoping that someone is listening to it.</li><li>Using global EventBus-es may cause multiple instances of the same class to receive the events if one of the instances is not unsubscribed correctly. For example:</li></ol><p><em>ActivityA</em> has started <em>ActivityB </em>and both of them are using the same fragment. And this fragment is receiving messages from some handler class via EventBus.</p><p>If the fragment is unsubscribed from <em>EventBus</em> in <em>onDestroy()</em> and not in <em>onStop() </em>then events will be received in both fragments (one in <em>ActivityA</em> and one in <em>ActivityB</em>).*</p><p>*- only if ActivityA wasn’t killed by the OS.</p><p>3. Even if you register/unregister in <em>onStart()</em>/<em>onStop()</em> you may have race conditions while using global EventBus. For example:</p><p><em>onStart()</em> of <em>ActivityB</em> is called before <em>onStop()</em> of <em>ActivityA </em>and if you send some events from <em>ActivityB </em>which are also received in <em>ActivityA </em>they may be received in a wrong place.</p><p>4. EventBus from Green DAO is hiding crashes <strong>if not configured correctly</strong>:</p><pre>Could not dispatch event: class com.myapp.message.PageStateMessage to subscribing class class com.myapp.fragments.PagerFragment<br>                                                       java.lang.NullPointerException: Attempt to invoke virtual method &#39;boolean com.myapp.ui.Page.getState()&#39; on a null object reference<br>                                                           at com.myapp.fragments.PagerFragment.onEventMainThread(VideoFragment.java:3054)</pre><p>BTW: I used <strong><em>MAT </em></strong>to find the mentioned memory leaks.</p><p>EventBus pattern may cause a lot of confusions and unexpected bugs. In general it is recommended to use local EventBus whenever is possible.</p><h3>Multiprocess sucks in so many ways.</h3><p>The main problems (in context of Android) with multiprocess are :</p><ol><li>You cannot use SharedPreferences in a normal way. Each process has its own SharedPreferences.</li><li>You cannot use Singleton pattern.</li></ol><p>I’ve been working a lot with multiprocess applications and trust me — it’s not something you want to deal with.</p><p>Each process is having it’s own SharedPreferences and even static members are different for different processes. This way the main problem is to have a good multiprocess storage.</p><p>Here are some libraries that <strong>DOES NOT HANDLE</strong> multiprocessing:</p><p><a href="https://github.com/realm/realm-java">Realm</a> — cool library but with many bugs.</p><p><a href="https://github.com/grandcentrix/tray">Tray</a> — creators of the library claim that it is multiprocess but on some devices there is an error with ContentProvider -it cannot be acquired for some reason.</p><p>The only reliable approach we’ve found is to use SQLite database for multiprocess storage and manage it by our own.</p><p>There are some advantages of using Multiprocess but it should probably covered in a different article.</p><h3>Doze mode and MediaCodec</h3><p>As you know Doze was introduced in <a href="https://developer.android.com/training/monitoring-device-state/doze-standby.html">Marshmallow</a>. And we have handled entering Doze mode in our application. In our application we use MediaCoded for encoding and decoding and it turned our that this is the place that has to be handled when device enters “Idle state” (Doze mode).</p><p>When we get and index of buffer from MediaCodec we might get a negative value which means that we need to do some additional action:</p><pre>switch(inputBufferIndex) {<br>    case MediaCodec.<em>INFO_TRY_AGAIN_LATER</em>:<br>        break;<br>    case MediaCodec.<em>INFO_OUTPUT_BUFFERS_CHANGED</em>:<br>        break;<br>    case MediaCodec.<em>INFO_OUTPUT_FORMAT_CHANGED</em>:<br>        break;<br>}</pre><p>So, when device enters Doze mode the MediaCodec always returns <strong>MediaCodec.<em>INFO_TRY_AGAIN_LATER </em></strong>and if you don’t handle that you may end in a situation with infinite retries. That is what happened with us so we have to add an additional check if we are in Doze, and if we are then break the loop.</p><pre>public boolean isInIdleState() {<br>    return Build.VERSION.<em>SDK_INT </em>&gt;= 23 &amp;&amp;</pre><pre>((PowerManager) mContext.getSystemService(Context.<em>POWER_SERVICE</em>))<br>        <br>    .isDeviceIdleMode();<br>}</pre><h3>Use a wrapper for the Log class.</h3><p>In my projects I use class Logger that is usual wrapper of Log class, but it has at least one big advantage over the regular Log class: it adds a thread id to the beginning of the string which makes a lot easier to debug multithread applications:</p><pre>class Logger {<br>    public int v(String TAG, String message) {<br>        return Log.<em>v</em>(TAG, <em>attachThreadId</em>(message));<br>    }<br>    private static String attachThreadId(String str){<br>        return Thread.<em>currentThread</em>().getId() + &quot; &quot; + str;<br>    }<br>    // ...other methods here<br>}</pre><p>Of course LogCat already gives us the ability to know if we are in “Main thread”:</p><blockquote>09–22 16:44:00.816 <strong>18386–18386</strong>/com.myapp V/log in UI thread<br>09–22 16:44:01.081 <strong>18386–19297</strong>/com.myapp V/log in other thread</blockquote><p>If first number (PID) equals to second number (TID) — UI thread.</p><p>If not — background thread.</p><p>I find more convenient to have a number in front of the log.</p><blockquote>09–22 16:44:00.816 <strong>18386–18386</strong>/com.myapp V/ <strong>1</strong> log in UI thread<br>09–22 16:44:01.081 <strong>18386–19297</strong>/com.myapp V/ <strong>1472 </strong>log in other thread</blockquote><h3>RxJava can be great replacement for AsyncTask.</h3><p>AsyncTask became obsolete with introduction of RxJava. RxJava is everywhere, tons of libraries are based on Rx.</p><p>It’s less verbose to use it and it gives you the ability to customize async operations whenever you want with usage of different operators.</p><p>Simple example:</p><p>I need to do some heavy operation with Bitmap. I could do it with AsyncTask but I’ve simply used Rx.</p><pre>class HandleBitmapObservable implements Observable.OnSubscribe&lt;Bitmap&gt;{</pre><pre>    private Bitmap mBitmap;</pre><pre>    HanldeBitmapObservable(Bitmap bitmap){<br>        mBitmap = bitmap;<br>    }</pre><pre>    @Override<br>    public void call(Subscriber&lt;? super Bitmap&gt; subscriber) {<br>        <br>        // .. do some heavy operations on mBitmap here</pre><pre>        // deliver the result of your work<br>        subscriber.onNext(mBitmap);<br>        <br>        // notify when you&#39;re done<br>        subscriber.onCompleted();</pre><pre>        // prevent potential memory leaks<br>        mBitmap = null;<br>    }</pre><pre>public static Observable&lt;Bitmap&gt; handleBitmap(Bitmap bitmap){</pre><pre>    return Observable.<em>create</em>(new HandleBitmapObservable(bitmap))<br>             <br>// Here you can choose in which thread the operation has <br>// to be done. You&#39;re not limited to a single thread. You can use<br>// ThreadExecutor. I use thread provided by &quot;Schedulers.<em>computation</em>()&quot;</pre><pre>    .subscribeOn(Schedulers.<em>computation</em>())</pre><pre>// Here you can choose in which thread the result will be delivered</pre><pre>    .observeOn(AndroidSchedulers.<em>mainThread</em>());<br>}</pre><pre>}</pre><p>Usage of this class is very simple:</p><pre>Subscription s = HanldeBitmapObservable.handleBitmap(bitmap)<br>.subscribe(<br>    new Action1&lt;Bitmap&gt;() {<br>        @Override<br>        public void call(Bitmap bitmap) {<br>            // use handled bitmap here<br>        }<br>    });</pre><pre>// do not forget to unsubscribe in onStop to prevent memory leaks<br>@Override<br>public void onStop(){<br>    super.onStop();<br>    s.unsubscribe();<br>}</pre><h3>Test your code with “Do not keep activities”.</h3><p>If you are an Android Developer and you don’t know what is a “Do not keep activities” (DNKA) you definitely need to go over the Developer options on your devices.</p><p>This flag helped us in so many cases. It simulates the Android behaviour when there is not enough memory and the activities that are not visible are killed by the OS. This situation even changes the lifecycle of your activity during receiving result from Activity you have started previously.</p><p>Here are some lifecycle callbacks and how they are called in relation to the state of DNKA flag in Developers options while receiving “Activity result”:</p><h4>With DNKA:</h4><ul><li>onCreate</li><li>onStart</li><li>onActivityResult</li></ul><h4>Without DNKA:</h4><ul><li>onActivityResult</li><li>onStart</li></ul><p>You’d be surprised of how many applications from Google Play you can force to crash just by browsing their screens when DNKA is turned on.</p><h3>About code convention.</h3><p>On our project we have a lot of legacy code that was written with our custom code convention. During last three years we had 9 permanent members that has already left the project. Instead of explaining code convention every time new member comes to the project we have decided to use standard code code convention kindly provided by Google.</p><p><a href="https://source.android.com/source/code-style.html">Code Style for Contributors</a></p><h3>Care about creating objects.</h3><p>As it usually is the main advantage of something can be also main disadvantage. I think that “Memory architecture” of Java is that kind of thing.</p><p>We don’t need to care about memory in most of the cases. Garbage collector will do everything for us. But in Android we need to care about memory a lot.</p><p>At some point we had this Architecture that was creating tons of objects — this caused huge problems for us.</p><p>There are libraries that demands creating a lot of objects when you use them. <a href="https://realm.io/">Realm </a>is a good example. If something demands from us to create a lot of new objects we think twice before adding it to our project.</p><p>We also had huge performance issues with logging. We have a lot of logs and when we checked how many objects we are creating we were shocked.</p><p><strong><em>Partial solution:</em></strong></p><p>We added proguard rules and everyone became happy. Remove debug and verbose logs.</p><p><em>proguar-rules.pro</em> file:</p><pre># Logging<br><strong>-assumenosideeffects </strong>class android.util.Log {<br>    public static boolean isLoggable(java.lang.String, int);<br>    public static int v(...);<br>    public static int d(...);<br>}</pre><p><em>build.gradle </em>file:</p><pre>release {<br>    signingConfig signingConfigs.release<br>    minifyEnabled true<br>    proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>    debuggable false<br>}</pre><p><em>proguard-android-optimize.txt</em> — it the key for this to work. If you don’t use this proguard file the usage of <em>Log.d()</em> and <em>Log.v()</em> will not be removed. But be carfull — some of the optimizations might harm your application. You will need good regression testing after this.</p><h3>Use Fabric for analytics.</h3><p><a href="https://fabric.io/home">Fabric </a>is a free tool for crash reporting and analytics. In analytics you can find some cool info like:</p><ul><li>Daily active users</li><li>Monthly active users</li><li>Daily new users</li><li>Crash-free users (one of my favourite)</li><li>Usage by devices</li><li>Usage by OS versions</li></ul><p>It’s also easy to use for reporting unexpected situations.</p><p><em>For example:</em></p><p>Assume there is a situation that should not happen in production but it will be wrong not to check the input values in this place. So you check if values are correct and if they are not you fallback gracefully and report to Fabric that “unexpected situation” has happened.</p><p>There are also other similar tools but I find this one very convenient and easy to integrate.</p><h3>Hungarian notation is useful for reading patches.</h3><p>If you’re doing code review on your project you’ve noticed that reading patches might be very confusing because you don’t always know the context of where in the code the changes has been made.</p><p>The Hungarian notation is very helpful here. It is easy to tell which types (static, non-static etc..) are these fields even without an IDE:</p><pre>SPEED_OF_LIGHT;<br>spaceShipName;<br>sLaunchPlatform;<br>mSpaceShipSpeed;</pre><p>There also a lot of other advantages for using it: <a href="https://en.wikipedia.org/wiki/Hungarian_notation">https://en.wikipedia.org/wiki/Hungarian_notation</a></p><h3>QA team are your friends.</h3><p>When I just started my career I didn’t have a good relationship with the QA team. I was arguing about some bugs they had logged, telling them: “It’s not a bug!”. And then I realized that the best approach is to tell: “Log it please and we will check”. In this case they feel appreciated for their job. Now, I cannot imagine a work on production without a QA. Who will cover my back if I screwed up? Having a QA is like a backup, you still have a good opportunity they will find your bugs instead of your users in production. Appreciate your QA and be grateful for the bugs they find for you to fix.</p><p>Actually, this is only 1% of the things I’d like to share. Maybe some day i will share the rest.</p><p>Cheers :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e56c27173ef4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/android-16-e56c27173ef4">Android 16</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Wear. Shared storage for smartwatch and the phone]]></title>
            <link>https://medium.com/android-development-by-danylo/android-wear-shared-storage-for-smartwatch-and-the-phone-7c8777b64238?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/7c8777b64238</guid>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:24:08 GMT</pubDate>
            <atom:updated>2018-02-25T21:13:51.170Z</atom:updated>
            <content:encoded><![CDATA[<p>Actually there is no “storage” for smartwatch and the phone. But there are some Wear API’s which can be used for this purpose.</p><p><a href="https://developer.android.com/training/wearables/data-layer/index.html">All the data was taken from this web page from Android Developers</a></p><p>I will show a one direction data transfer: <strong><em>from handhold to the smartwatch</em></strong></p><p>But he same techniques can be used to transfer data: <em>from smartwatch to the handhold</em></p><p>So this article is about:</p><ol><li>How to save data using Wear API’s</li><li>How to get saved data on the watch</li><li>How to listen to the data changes on the wear</li><li>How to remove data from the storage</li></ol><h4>How to save data using Wear API’s</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*SKOYyDXzC_xgtgzdatsipw.png" /></figure><p>We need to understand that all this is happening asynchronously over the cloud. Device which is saving the data does it with implicitly specified “node id”. This “node id” is the unique identifier of the device that stores the data.</p><p>Technically a single smartwatch can access data from multiple nodes which basically means multiple phones(tablets)</p><p><em>On you phone (tablet):</em></p><ol><li>Create a <strong>PutDataMapRequest</strong> object</li><li>Get map object from it and put data to it. Here is the list of methods we can use to put data:</li></ol><pre>public void putBoolean(String key, boolean value)<br>public void putByte(String key, byte value)<br>public void putInt(String key, int value)<br>public void putLong(String key, long value)<br>public void putFloat(String key, float value)<br>public void putDouble(String key, double value)<br>public void putString(String key, String value)<br>public void putAsset(String key, Asset value)<br>public void putDataMap(String key, DataMap value)<br>public void putByteArray(String key, byte[] value)<br>public void putLongArray(String key, long[] value)<br>public void putFloatArray(String key, float[] value)<br>public void putStringArray(String key, String[] value)<br>public void putStringArrayList(String key, ArrayList&lt;String&gt; value)<br>public void putDataMapArrayList(String key, ArrayList&lt;DataMap&gt; value)<br>public void putIntegerArrayList(String key, ArrayList&lt;Integer&gt; value)</pre><p>3. Create a <strong>PutDataRequest</strong> from <strong>PutDataMapRequest </strong>to send the data into “Wearable” storage(the could node) by using <strong>DataClient</strong></p><pre>private val TAG = &quot;TAG&quot;<br>private val pathToYourData = &quot;/path-to-your-data&quot;<br>private val KEY_NAME = &quot;KEY_NAME&quot;</pre><pre>/**<br> * <strong>We need to fetch DataClient to work with a PutDataMapRequest</strong> <br> */<br>private val mDataClient = Wearable.getDataClient(context)</pre><pre>/**<br> * <strong>Create a putDataMapRequest</strong><br> */<br>val putDataMapReq = PutDataMapRequest.create(pathToYourData)</pre><pre>/**<br> * <strong>Get the DataMap object from the request</strong><br> */<br>val dataMap = putDataMapReq.<em>dataMap</em></pre><pre>/**<br> * <strong>Add the data to the map</strong><br> */<br>dataMap.putString(KEY_NAME, &quot;Danylo&quot;)</pre><pre>/**<br> * <strong>Get the putDataRequest</strong><br> */<br>var putDataReq = putDataMapReq.asPutDataRequest()</pre><pre>/**<br> * <strong>Put DataItem into the mDataClient object</strong><br> */<br>val putDataTask = mDataClient.putDataItem(putDataReq)</pre><pre>/**<br><strong> * Here is a very important moment. The last step can be done in<br> * two ways<br> *<br> *  - synchronous<br> *  - asynchronous</strong><br> */</pre><pre>// synchronous<br>val result = Tasks.await(putDataTask)</pre><pre><strong>// OR</strong></pre><pre>// asynchronous        <br>putDataTask.addOnCompleteListener(<strong>{<br>    </strong>Log.v(TAG, &quot;saveWearableData complete listener <br><strong>}</strong>)</pre><p>Synchronous has to be done in separate thread from the main:</p><pre>val result = Tasks.await(putDataTask)</pre><p>Asynchronous can be done on the main thread and after it’s done the complete callback will be invoked</p><pre>putDataTask.addOnCompleteListener(<strong>{<br>    </strong>Log.v(TAG, &quot;saveWearableData complete listener <br><strong>}</strong>)</pre><blockquote>If a delay in syncing would negatively impact user experience, call <a href="https://developer.android.com/reference/com/google/android/gms/wearable/PutDataRequest#setUrgent()">setUrgent()</a>.</blockquote><p>When creating a putDataRequest object:</p><pre>var putDataReq = putDataMapReq<br>                .asPutDataRequest()<br>                .setUrgent()</pre><h4>How to get saved data on the watch</h4><p><em>On you smartwatch:</em></p><p>You can do this in your Activity, Service or anywhere. You just need to have context. You have to make it in few steps:</p><ol><li>Get the “node id” which was used to store the data. This “node id” represents the device which stored this data. We can get a list of nodes (devices) which are synchronized with our smartwatch. This device not necessarily has to be connected right now (devices can be temporarily disconnected) you will still get this device and the node it created.</li><li>Use this “node id” to get the data which was stored on that node.</li><li>Find your data using path. The same path we used when we stored the data.</li></ol><p><strong>This is the synchronous way so it has to be done is a separate thread (not the UI)</strong></p><pre>private val KEY_NAME = &quot;KEY_NAME&quot;</pre><pre>var nodeId: String? = null<br>/**<br> * <strong>Get the node id first </strong><br> */</pre><pre>val nodesTask = Wearable.getNodeClient(this).<em>connectedNodes</em></pre><pre>/**<br> * <strong>Execute the task synchronously</strong><br> */</pre><pre>val results = Tasks.await(nodesTask)</pre><pre>/**<br> * <strong>You can choose your own criteria to get necessary node</strong><br> *<br> * <strong>Here we iterate over all the nodes and :</strong><br> * <strong>- Skip devices that are not &quot;nearby&quot;. </strong><br> * <strong>- Choose first connected node and then &quot;break&quot; from the loop</strong><br> */</pre><pre>for (node in results) {<br><br>    Log.v(TAG, &quot;getNodeIdWithData, node.isNearby ${node.<em>isNearby</em>}&quot;)<br><br>    if (!node.<em>isNearby</em>) {<em><br></em>        continue<br>    }<br><br>    Log.v(TAG, &quot;getNodeIdWithData, node.isNearby ${node.<em>isNearby</em>}&quot;)</pre><pre>    /**<br>     * <strong>Get the id from the node</strong><br>     */</pre><pre>    nodeId = node.<em>id</em></pre><pre><em>    </em><strong><em>/**<br>     * We handle first data that we found<br>     */</em></strong><em><br>    </em>break<br>}</pre><pre><br>val pathToYourData = &quot;/path-to-your-data&quot;</pre><pre>/**<br><strong> * Create the uri which we use to access the &quot;node&quot; data</strong><br> */<br>val uri = Uri.Builder()<br>        .scheme(PutDataRequest.<em>WEAR_URI_SCHEME</em>)<br>        .path(pathToYourData)<br>        .authority(nodeId)<br>        .build()<br><br>val dataItem = Wearable.getDataClient(this).getDataItem(uri)<br>val result = Tasks.await(dataItem)</pre><pre>/**<br> * <strong>Here we need to check the result for null. I&#39;ve noticed that </strong><br> * <strong>sometimes it can be null.</strong><br> */</pre><pre>if(result != null){</pre><pre>    /**<br>     * <strong>Get the map we created during storing the data.</strong><br>     */</pre><pre>    val dataMap = DataMapItem.fromDataItem(result).<em>dataMap<br></em>    val name = dataMap.getString(KEY_NAME)</pre><pre>    // name = &quot;Danylo&quot;<br>}</pre><p>If you don’t want to run a separate thread you can wait for Task completion with OnCompleteListener</p><pre>// Instead of synchronous <strong>val result = Tasks.await(task)</strong></pre><pre>// asynchronous        <br>task.addOnCompleteListener(<strong>{<br>    </strong>Log.v(TAG, &quot;complete listener <br><strong>}</strong>)</pre><h4>How to listen to the data changes on the wear</h4><p><em>On you smartwatch:</em></p><p>This can be done 2 ways</p><ul><li>Locally in the Activity</li><li>In the Service</li></ul><p>Here is how it’s done in the activity:</p><pre>private val KEY_NAME = &quot;KEY_NAME&quot;<br>private val pathToYourData = &quot;/path-to-your-data&quot;</pre><pre>/**<br> * <strong>Subscribe the listener on in onResume</strong><br> */<br>override fun onResume() {<br>    super.onResume()<br>    Log.v(TAG, &quot;onResume&quot;)<br>    Wearable.getDataClient(this).addListener(this)<br>}</pre><pre>/**<br> * <strong>Unsubscribe the listener on in onPause</strong><br> */<br>override fun onPause() {<br>    super.onPause()<br>    Log.v(TAG, &quot;onPause&quot;)<br>    Wearable.getDataClient(this).removeListener(this)<br>}</pre><pre>/**<br> * <strong>This method will be called when changes in the data will be done</strong><br> */</pre><pre>override fun onDataChanged(dataBuffer: DataEventBuffer) {<br>    Log.v(TAG, &quot;&gt;&gt; onDataChanged, dataBuffer &quot; + dataBuffer)<br><br>    for (event in dataBuffer) {<br>        Log.v(TAG, &quot;onDataChanged, event getType&quot; + event.getType())<br><br>        when(event.<em>type</em>){</pre><pre>           /**<br>            * <strong>We get this event type it data was created or</strong><br>            * <strong>changed</strong><br>            */<br>           DataEvent.<em>TYPE_CHANGED </em>-&gt;{<br>                val item = event.<em>dataItem<br>                </em>Log.v(TAG, &quot;onDataChanged, item &quot; + item)<br>                <br>                val uri = item.<em>uri<br>                val path = uri.path</em></pre><pre>                /**<br>                 * <strong>We compare the path to find our path</strong><br>                 */  </pre><pre>                if (<em>path</em>.compareTo(pathToYourData) == 0) {<br>                    /**<br>                     * <strong>&quot;authority&quot; from the uri the the NodeID<br>                     */</strong></pre><pre>                    nodeId = item.<em>uri</em>.<em>authority</em></pre><pre>                    val dataItem = DataMapItem.fromDataItem(item)<br>                    val dataMap = dataItem.<em>dataMap<br>                    <br></em>                    val name = dataMap.getString(KEY_NAME)</pre><pre>                }<br>            }</pre><pre>           /**<br>            * <strong>We get this event type it data was created or</strong><br>            * <strong>changed</strong><br>            */<br>            DataEvent.<em>TYPE_DELETED </em>-&gt; {<br>                Log.v(TAG, &quot;onDataChanged, item deleted&quot;)<br>                // handle data deletion hear<br>            }<br>        }<br>    }<br>    Log.v(TAG, &quot;&lt;&lt; onDataChanged, dataBuffer &quot; + dataBuffer)<br>}</pre><p>In order to continuously listen to the changes in the service you need to implement <strong>WearableListenerService</strong></p><p>And implement the same method <strong>onDataChanged </strong>as we did in Activity:</p><pre>override fun onDataChanged(dataEvents: DataEventBuffer) {</pre><pre><strong>// handle data changes here. Store the data locally or do anything // you need.</strong></pre><pre>}</pre><p>Define your service in <strong>AndroidManifest.xml</strong> of wear application</p><pre>&lt;service android:name=&quot;.service.NameOfYourService&quot; &gt;</pre><pre>&lt;intent-filter&gt;</pre><pre>   &lt;action <br>    android:name=&quot;com.google.android.gms.wearable.DATA_CHANGED&quot;/&gt;</pre><pre>   &lt;data <br>    android:scheme=&quot;wear&quot; <br>    android:host=&quot;*&quot; <br>    android:pathPrefix=&quot;/path-to-your-data&quot; /&gt;</pre><pre>&lt;/intent-filter&gt;</pre><pre>&lt;/service&gt;</pre><p>This way you will get all the “data update” and “data deleted” events in the service. Use it to listen to the changes in background.</p><h4>How to remove data from the storage</h4><p><em>On you phone(tablet):</em></p><pre>private val pathToYourData = &quot;/path-to-your-data&quot;</pre><pre>val uri = Uri.Builder()<br>        .scheme(PutDataRequest.<em>WEAR_URI_SCHEME</em>)<br>        .path(pathToYourData)<br>        <em>/**<br>         * wildcard means delete path from all the nodes<br>         */<br>        </em>.authority(&quot;*&quot;)<br>        .build()<br><br>Wearable.getDataClient(context).deleteDataItems(uri)</pre><p>After this on your smartwatch you will get a data change event with type <strong>DataEvent.<em>TYPE_DELETED</em></strong></p><p>And that’s it.</p><p>Cheers ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8777b64238" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/android-wear-shared-storage-for-smartwatch-and-the-phone-7c8777b64238">Android Wear. Shared storage for smartwatch and the phone</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up a Free CI for Android project based on Bitbucket Cloud Pipelines]]></title>
            <link>https://medium.com/android-development-by-danylo/how-to-set-up-a-free-ci-for-android-project-based-on-bitbucket-cloud-pipelines-5b27d0a96b78?source=rss----b1baad4cfa74---4</link>
            <guid isPermaLink="false">https://medium.com/p/5b27d0a96b78</guid>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Danylo Volokh]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 19:20:18 GMT</pubDate>
            <atom:updated>2019-03-27T11:30:54.628Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Link to Github:</strong> <a href="https://github.com/danylovolokh/Setup-Free-Bitbucket-Cloud-CI">https://github.com/danylovolokh/Setup-Free-Bitbucket-Cloud-CI</a></p><p>This project is created as a “manual” for setting up a FREE CI (Continuous Integration) based on Bitbucket Pipelines <a href="https://bitbucket.org/product/features/pipelines">https://bitbucket.org/product/features/pipelines</a>)</p><p>At the time of writing (10.03.2019) <strong>bitbucket cloud offers you a free 50 build minutes</strong> to get started with Pipelines.</p><h4>List of files needed in this project to setup CI</h4><p>All those files are on the Github: <a href="https://github.com/danylovolokh/Setup-Free-Bitbucket-Cloud-CI">https://github.com/danylovolokh/Setup-Free-Bitbucket-Cloud-CI</a></p><pre>- ./build_info.json<br>- ./1_update_build_info_json.py<br>- ./2_update_gradle_build_version.py<br>- ./3_commit_build_version.py<br>- ./4_collect_change_log.py<br>- ./6_upload_apk_file_to_bitbucket_downloads.py<br>- ./Utils.py</pre><h4>Steps to build a version with Bitbucket Pipelines</h4><p>1. Update build number, build version name etc…<br>2. Update build.gradle<br>3. Commit and push changes to the repository<br>4. Collect a changelog<br>5. Build the application</p><h4>Additional steps:</h4><p>6. Sign the application with the “release” signing key.<br>7. Upload the apk files to the storage for future usage.<br>8. Upload a version to the Fabric Beta for testing purposes.</p><h4>1. Update build number, build version name etc…</h4><p>We will use <strong>build_info.json</strong> to keep the build history.<br>The file <strong>build_info.json</strong> is located in the root of the project.</p><p>Example:</p><pre>Example:<br>{<br>“build_number”:”13&quot;,<br>“build_date”:”2019–03–10 09:36&quot;,<br>“previous_build_date”:”2019–03–10 09:16&quot;,<br>“application_name”:”SetupBitbucketCloudCI”,<br>“application_version”:”1.0&quot;,<br>“build_tag”:”SetupBitbucketCloudCI/1.0/13&quot;,<br>“previous_build_tag”:”SetupBitbucketCloudCI/1.0/12&quot;,<br>“repo_url”:”ssh://<a href="/service/mailto:git@bitbucket.org">git@bitbucket.org</a>:DanyloVolokh/setupbitbucketcloudci.git”,<br>“git_branch”:”master”<br>}</pre><p>- <strong>build_number</strong> — this value is a build number<br>- <strong>build_date</strong> — date, when this build was created<br>- <strong>previous_build_date</strong> — the date of the previous build<br>- <strong>application_name</strong> — to change the application name, change this value<br>- <strong>application_version</strong> — to change the application version (example: from 1.1 to 2.0) you need to change this value<br>- <strong>build_tag</strong> — a tag name which will be added to the repository when the build is created<br>- <strong>previous_build_tag</strong> — a tag which was added when the previous build was created <br>- <strong>repo_url</strong> — link to the repository<br>- <strong>git_branch</strong> — to work on a different branch beside master you need to change this value</p><p>To update the *build_info.json* we need to execute the python script <strong>1_update_build_info_json.py</strong></p><p>The file <strong>1_update_build_info_json.py</strong> is located in the root of the project.</p><p>This script makes following changes to the *build_info.json*:<br>- increments <strong>build_number</strong><br>- changes <strong>build_date</strong> to the current date<br>- updates <strong>previous_build_date</strong><br>- updates <strong>build_tag</strong><br>- updates <strong>previous_build_tag</strong></p><h4>2. Update build.gradle</h4><p>We need to modify 2 files:<br>- <strong>build.gradle</strong> file of the “app” module<br>- <strong>build.gradle</strong> of the root.</p><p>The file <strong>build.gradle</strong> is located in the root of the project.</p><pre>ext {<br> versionCodeValue = 9999<br> versionNameValue = “debugApplication”<br>}</pre><p>The file <strong>build.gradle</strong> is located in the “app” folder of the project.</p><pre> defaultConfig {<br> …<br> versionName versionNameValue<br> versionCode versionCodeValue<br> …<br> }</pre><p>To update “versionNameValue” and “versionCode” in the build.gradle we need to execute python script “2_update_gradle_build_version.py”</p><p>The file <strong>2_update_gradle_build_version.py</strong> is located in the root of the project.</p><p>This script takes the <strong>application_name</strong> and <strong>application_version</strong> from <strong>build_info.json</strong>, creates a <strong>versionNameValue</strong> and adds it to the root <strong>build.gradle</strong>. Values in the root <strong>build.gradle</strong> are used as <strong>versionName</strong> and <strong>versionCode</strong> in the <strong>build.gradle</strong> of the “app” module.</p><pre>versionNameValue = application_version + ‘.’ + build_number<br>versionCodeValue = build_number</pre><h4>3. Commit and push changes to the repository</h4><p>To commit the changes to build_info.json we need to execute python script <strong>3_commit_build_version.py</strong></p><p>The file <strong>3_commit_build_version.py</strong> is located in the root of the project.<br>Please note: we do not commit “build.gradle” files. We only modify the <strong>build_info.json</strong></p><h4>4. Collect a changelog</h4><p>To collect the change log we need to execute python script <strong>4_collect_change_log.py</strong></p><p>The file <strong>4_collect_change_log.py</strong> is located in the root of the project.</p><p>Change contains all the commit messages from the commits between this build and the previous build.</p><p>In this project, we create separate changelog files for every flavor of the application. Then these separate change logs can be used as a “Release Notes” when we upload different versions to the Fabric. Because the only way to distinguish “flavors” in Fabric Beta “Release notes” is to have different release notes, we create separate changelog files for each flavor.</p><p>After you run <strong>4_collect_change_log.py</strong> 2 new files will be created in the root of the project:<br><em>- change_log_external.txt<br>- change_log_internal.txt</em></p><p>The changelog is collected between the <strong>build_tag</strong> and <strong>previous_build_tag</strong>.<br>Example of the <strong>change_log_external.txt</strong></p><pre>External</pre><pre>“Added how to commit changes”<br>“Added how to update build.gradle file”<br>“Added initial Readme file”<br>“Fix files that were committed by mistake”<br>“Update upload to Downloads”</pre><h4>5. Build the application</h4><p>Now we are ready to build a “debug” version with bitbucket CI. To be able to build a “release” version we need to setup the signing key.<br>In order to build the “debug” version, we need to call “./gradlew assembleDebug”</p><pre>./gradlew assembleDebug</pre><h4>Setup Bitbucket pipelines.</h4><p>References:</p><ol><li>Get started with Bitbucket Pipelines <a href="https://confluence.atlassian.com/bitbucket/get-started-with-bitbucket-pipelines-792298921.html">https://confluence.atlassian.com/bitbucket/get-started-with-bitbucket-pipelines-792298921.html</a></li><li>Configure bitbucket-pipelines.yml <a href="https://confluence.atlassian.com/bitbucket/configure-bitbucket-pipelines-yml-792298910.html">https://confluence.atlassian.com/bitbucket/configure-bitbucket-pipelines-yml-792298910.html</a></li></ol><p>In order to setup bitbucket pipelines, you need to add the <strong>bitbucket-pipelines.yml</strong> file to the root of the project.</p><pre>pipelines:<br> custom:<br> manual_configuration:<br> — step:<br> name: Build a version<br> image: openjdk:8<br> caches:<br> — gradle<br> — android-sdk<br> — pip<br> script:</pre><pre># Download and unzip android sdk<br> — wget — quiet — output-document=android-sdk.zip <a href="https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip">https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip</a><br> — unzip -o -qq android-sdk.zip -d android-sdk</pre><pre># Define Android Home and add PATHs<br> — export ANDROID_HOME=”/opt/atlassian/pipelines/agent/build/android-sdk”<br> — export PATH=”$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH”</pre><pre># Download packages.<br> — yes | sdkmanager “platform-tools”<br> — yes | sdkmanager “platforms;android-27”<br> — yes | sdkmanager “build-tools;27.0.3”<br> — yes | sdkmanager “extras;android;m2repository”<br> — yes | sdkmanager “extras;google;m2repository”<br> — yes | sdkmanager “extras;google;instantapps”<br> — yes | sdkmanager — licenses</pre><pre># Install python<br> — echo “Install python”<br> — apt-get update<br> — apt-get install python-pip -q -y</pre><pre># Give write access<br> — chmod a+x ./gradlew</pre><pre># Clean the project<br> — ./gradlew clean</pre><pre># Setup correct origin url<br> — git config -e<br> — git config — global user.email “<a href="/service/mailto:v.danylo@gmail.com">v.danylo@gmail.com</a>”<br> — git config — global user.name “Danylo Volokh Pipeline”<br> — git config remote.origin.url <a href="https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$GIT_REPO_NAME.git">https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$GIT_REPO_NAME.git</a></pre><pre># Change build version<br> — echo “Update info json”<br> — python 1_update_build_info_json.py</pre><pre># Update application version in gradle file<br> — echo “Change build version”<br> — python 2_update_gradle_build_version.py</pre><pre># Change build version after successful build<br> — echo “Commit build version”<br> — python 3_commit_build_version.py</pre><pre># Collect change log<br> — echo “Collect change log”<br> — python 4_collect_change_log.py</pre><pre># Build apk<br> — ./gradlew assembleDebug</pre><pre>definitions:<br> caches:<br> android-sdk: android-sdk</pre><p>Then you have to enable Bitbucket Pipelines in the Settings of your account “Settings &gt; Pipelines”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qI7KuGMZe966RNZAKKwY8A.gif" /></figure><p>You also need to add a few variables to the “Repository variables” of the Pipelines section in the Settings.<br>- <strong>BITBUCKET_USER</strong> — user which has access to write to the master branch<br>- <strong>BITBUCKET_PASS</strong> — password to this user (password will be encrypted and hidden from everyone else)<br>- <strong>BITBUCKET_ACCOUNT</strong> — account on which the repository is stored<br>- <strong>GIT_REPO_NAME</strong> — the name of the repository</p><p>The values above will be used to access the git repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Va37_rwf3x2VyaBWlPSe4g.png" /></figure><p>Now you are ready to build the “debug” version with Bitbucket Pipelines</p><p>Additional steps</p><h4>6. Sign the application with the “release” signing key.</h4><p>This is a tricky moment because you need to give the Pipelines an access to your signing key but do not commit it into the repository. The signing key should not be available to all the team members that have access to the repository.</p><p>In order to download the signing key into the repository only for the builds with Bitbucket Pipelines we need to create a “secret repository” as a git submodule. This repository will be located in “signing_info_from_another_repository”.</p><p>1.Create a separate repository with 2 files in the root of the project.<br>“<strong>playstore.properties</strong>”:</p><pre>storeFile=keystore_file<br>storePassword=store_password<br>keyAlias=key<br>keyPassword=keyPassword</pre><p>“<strong>keystore_file</strong>”:<br>This is a keystore file with your signing key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zghFg4cEDqQ6i_Ox3A-oMg.png" /></figure><p>2. Now we have to add this repository as a git submodule. Call the following command in the main repository.</p><p><em>git submodule add &lt;url&gt; signing_info_from_another_repository</em></p><p>3. Add signing configuration to the “*app/build.gradle file*”</p><p>Add this to the top of the “<strong>app/build.gradle file</strong>”</p><pre>def signingPropertiesFile = new File(‘./signing_info_from_another_repo/playstore.properties’)<br>def keystoreProperties = new Properties()<br>if (signingPropertiesFile &amp;&amp; signingPropertiesFile.isFile()) {<br> println “signingPropertiesFile.isFile()”<br> keystoreProperties.load(new FileInputStream(signingPropertiesFile))<br>}</pre><p>Add signing cofig to the “*android*” closure:</p><pre><br>android {<br> signingConfigs {<br> <br>   debug {<br>   }<br> <br>   release {<br>      def keystoreFilePath =<br>“${rootDir}/signing_info_from_another_repo/${keystoreProperties[‘storeFile’]}”<br>    <br>      storeFile = file(keystoreFilePath)<br>      storePassword = keystoreProperties[‘storePassword’]<br>      keyAlias = keystoreProperties[‘keyAlias’]<br>      keyPassword = keystoreProperties[‘keyPassword’]<br>   }<br> }<br> <br>buildTypes {<br> <br>  release {<br>     signingConfig signingConfigs.release<br>  }<br> }<br>}</pre><p>4. Update <strong>bitbucket-pipelines.yml</strong> file:</p><p>Add the following code which will clone the signing configuration for the build:</p><pre># Download signing key<br>- echo “Download signing key”<br>- git config — file=.gitmodules submodule.signing_info_from_another_repo.url <a href="https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$SIGNING_REPO_NAME.git">https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$SIGNING_REPO_NAME.git</a><br>- git submodule sync<br>- git submodule update — init signing_info_from_another_repo</pre><p>But this code used the following variables:<br>- <strong>BITBUCKET_USER</strong> — already added above<br>- <strong>BITBUCKET_PASS</strong> — already added above<br>- <strong>BITBUCKET_ACCOUNT</strong> — already added above<br>- <strong>SIGNING_REPO_NAME</strong> — name to the signing repo name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl-j2U516CxH4EDeGjCJIw.png" /></figure><p>5. change “assembleDebug” to “assembleRelease”<br>Here is an updated <strong>bitbucket-pipelines.yml</strong> file</p><pre>pipelines:<br> custom:<br> manual_configuration:<br> — step:<br> name: Build a version<br> image: openjdk:8<br> caches:<br> — gradle<br> — android-sdk<br> — pip<br> script:</pre><pre># Download and unzip android sdk<br> …<br> <br> # Define Android Home and add PATHs<br> …<br> <br> # Download packages.<br> …<br> <br> # Install python<br> …<br> <br> # Give write access<br> — chmod a+x ./gradlew<br> <br> # Clean the project<br> — ./gradlew clean<br> <br> # Setup correct origin url<br> …</pre><pre># Change build version<br> …</pre><pre># Update application version in gradle file<br> …</pre><pre># Change build version after successful build<br> …</pre><pre># Collect change log<br> …</pre><pre># Download signing key<br> — echo “Download signing key”<br> — git config — file=.gitmodules submodule.signing_info_from_another_repo.url <a href="https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$SIGNING_REPO_NAME.git">https://$BITBUCKET_USER:$BITBUCKET_PASS@bitbucket.org/$BITBUCKET_ACCOUNT/$SIGNING_REPO_NAME.git</a><br> — git submodule sync<br> — git submodule update — init signing_info_from_another_repo</pre><pre># Build apk<br> — ./gradlew assembleRelease</pre><pre>definitions:<br> caches:<br> android-sdk: android-sdk<br></pre><p>Now you are ready to build the “release” version with Bitbucket Pipelines</p><h4>7. Upload the apk files to the storage for future usage.</h4><p>We can use the Downloads folder of the bitbucket cloud to keep the artifacts of our build.</p><p>To upload the apk files of all the flavors we need to execute python script <strong>6_upload_apk_file_to_bitbucket_downloads.py</strong></p><p>The file <strong>6_upload_apk_file_to_bitbucket_downloads.py</strong> is located in the root of the project.</p><p>Publish and link your build artifacts <a href="https://confluence.atlassian.com/bitbucket/publish-and-link-your-build-artifacts-872137736.html">https://confluence.atlassian.com/bitbucket/publish-and-link-your-build-artifacts-872137736.html</a></p><p>This file used default bitbucket API to upload files into the repository.<br>In order to do that we need:</p><p>1. Add one Environment variable to the Account Setting (not the repository settings)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyCp2UAoNr5sObkGGTHkfQ.png" /></figure><p>- <strong>BB_AUTH_STRING</strong> — this variable consists of the account and password separated by the colon “:”</p><p>2. Call “<strong>6_upload_apk_file_to_bitbucket_downloads.py</strong>” from <strong>bitbucket-pipelines.yml</strong></p><p>Here is an updated *<strong>bitbucket-pipelines.yml</strong> file:</p><pre>pipelines:<br> custom:<br> manual_configuration:<br> — step:<br> name: Build a version<br> image: openjdk:8<br> caches:<br> — gradle<br> — android-sdk<br> — pip<br> script:</pre><pre># Download and unzip android sdk<br> …<br> <br> # Define Android Home and add PATHs<br> …<br> <br> # Download packages.<br> …<br> <br> # Install python<br> …<br> <br> # Give write access<br> — chmod a+x ./gradlew<br> <br> # Clean the project<br> — ./gradlew clean<br> <br> # Setup correct origin url<br> …</pre><pre># Change build version<br> …</pre><pre># Update application version in gradle file<br> …</pre><pre># Change build version after successful build<br> …</pre><pre># Collect change log<br> …</pre><pre># Download signing key<br> …</pre><pre># Build apk<br> — ./gradlew assembleRelease<br> <br> # Upload apk files to bitbucket cloud Downloads folder<br> — echo “Upload apk files to bitbucket cloud Downloads folder”<br> — python 6_upload_apk_file_to_bitbucket_downloads.py</pre><pre>definitions:<br> caches:<br> android-sdk: android-sdk<br> </pre><p>Here is how uploaded files look like in the storage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iB6oOdo1MddjKuemfTVI-Q.png" /></figure><h4>8. Upload a version to the Fabric Beta for testing purposes.</h4><p>In order to upload a version to Fabric Beta you need to setup the Fabric Beta first.</p><p>- Install Crashlytics via Gradle <a href="https://fabric.io/kits/android/crashlytics/install">https://fabric.io/kits/android/crashlytics/install</a><br>- Beta Instalation <a href="https://docs.fabric.io/android/beta/installation.html">https://docs.fabric.io/android/beta/installation.html</a></p><p>If you already upload the files to the Fabric Beta we need to add 2 more changes to the configuration:</p><p>1. Change the <strong>bitbucket-pipelines.yml</strong> <br>add “crashlyticsUploadDistributionExternalRelease crashlyticsUploadDistributionInternalRelease -Dorg.gradle.parallel=false” after the “assembleRelease”</p><pre>./gradlew assembleRelease crashlyticsUploadDistributionExternalRelease crashlyticsUploadDistributionInternalRelease -Dorg.gradle.parallel=false</pre><p>2. Change the <strong>app/build.gradle</strong> <br>We need to add the correct “Release Notes” with every flavor that we upload</p><pre>flavorDimensions “default”<br>productFlavors {</pre><pre>external {<br> dimension “default”</pre><pre> ext.betaDistributionReleaseNotesFilePath = “change_log_external.txt”</pre><pre> ext.betaDistributionApkFilePath = “${buildDir}/outputs/apk/internal/release/app-external-release.apk”</pre><pre> ext.betaDistributionGroupAliases = “testing-group-setup-ci”<br> }</pre><pre>internal {<br> dimension “default”</pre><pre> ext.betaDistributionReleaseNotesFilePath = “change_log_internal.txt”</pre><pre> ext.betaDistributionApkFilePath = “${buildDir}/outputs/apk/external/release/app-internal-release.apk”</pre><pre> ext.betaDistributionGroupAliases = “testing-group-setup-ci”<br> }<br> }<br></pre><h4>Run the CI</h4><p>We are all set. Now we can easily run our build server from the bitbucket page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irSxa9bAj9krXPjoDfP5Qw.gif" /></figure><h4>Successful build</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMlChP4LhV8Xj7_vZ2FQbg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b27d0a96b78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-development-by-danylo/how-to-set-up-a-free-ci-for-android-project-based-on-bitbucket-cloud-pipelines-5b27d0a96b78">How to set up a Free CI for Android project based on Bitbucket Cloud Pipelines</a> was originally published in <a href="https://medium.com/android-development-by-danylo">Android Development by Danylo :)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>