<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Grokking Android</title>
	<atom:link href="https://www.grokkingandroid.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.grokkingandroid.com/</link>
	<description>Getting Down to the Nitty Gritty of Android Development</description>
	<lastBuildDate>Thu, 08 Jan 2026 18:09:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>The Different Node Types in Jetpack Compose</title>
		<link>https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/</link>
					<comments>https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 30 Dec 2025 15:32:14 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<guid isPermaLink="false">https://www.grokkingandroid.com/?p=4704</guid>

					<description><![CDATA[<p>If you look at Compose it's weird. You have tons of functions that return nothing. Yet the Android documentation says: Composable functions emit UI hierarchy. What does this actually mean? Well, from a functional programming point of view your innocuous looking stateless composable functions create loads of side effects1). Among other things they create nodes. [...]&#160;&#160;<a href="https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/">Continue Reading&#160;&#160;"The Different Node Types in Jetpack Compose"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/">The Different Node Types in Jetpack Compose</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p class="image">
<img fetchpriority="high" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode-700x389.png" alt="Teaser showing a partial listing of ComposeUiNode" width="700" height="389" class="aligncenter size-large wp-image-4776" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode-700x389.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode-500x278.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode-768x427.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode-1536x855.png 1536w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2025/12/ComposeUiNode.png 1704w" sizes="(max-width: 700px) 100vw, 700px" />
</p>
<p>If you look at Compose it's weird. You have tons of functions that return nothing. Yet the <a href="https://developer.android.com/develop/ui/compose/mental-model">Android documentation</a> says:</p>
<blockquote><p>Composable functions emit UI hierarchy.</p></blockquote>
<p>What does this actually mean? Well, from a functional programming point of view your innocuous looking stateless composable functions create loads of side effects<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_1');" onkeypress="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_1');" ><sup id="footnote_plugin_tooltip_4704_2_1" class="footnote_plugin_tooltip_text">1)</sup></a><span id="footnote_plugin_tooltip_text_4704_2_1" class="footnote_tooltip"></span></span>. Among other things they create nodes. </p>
<p>Sometimes you might create Composables that create nodes yourself. But more often you will simply delegate to other Composables that then create the nodes.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_2');" onkeypress="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_2');" ><sup id="footnote_plugin_tooltip_4704_2_2" class="footnote_plugin_tooltip_text">2)</sup></a><span id="footnote_plugin_tooltip_text_4704_2_2" class="footnote_tooltip"></span></span></p>
<p>So let's have a look at what nodes we have, where they are created and what purpose they fulfill:</p>
<ul>
<li>ComposeUiNode</li>
<li>LayoutNode</li>
<li>Modifier.Node</li>
<li>SemanticsNode</li>
</ul>
<h3 id="">ComposeUiNode</h3>
<p>When you dig into the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/package-summary#Layout(androidx.compose.ui.Modifier,androidx.compose.ui.layout.MeasurePolicy)"><code class="preserve-code-formatting">Layout</code></a> composable you see that it calls <code class="preserve-code-formatting">ReusableComposeNode</code>:<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_3');" onkeypress="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_3');" ><sup id="footnote_plugin_tooltip_4704_2_3" class="footnote_plugin_tooltip_text">3)</sup></a><span id="footnote_plugin_tooltip_text_4704_2_3" class="footnote_tooltip"></span></span>:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="7,8"><code class="language-kotlin line-numbers">
@Composable
@UiComposable
inline fun Layout(modifier: Modifier = Modifier, measurePolicy: MeasurePolicy) {
    val compositeKeyHash = currentCompositeKeyHash
    val materialized = currentComposer.materialize(modifier)
    val localMap = currentComposer.currentCompositionLocalMap
    ReusableComposeNode&lt;ComposeUiNode, Applier&gt;(
        factory = ComposeUiNode.Constructor,
        update = {
            set(measurePolicy, SetMeasurePolicy)
            set(localMap, SetResolvedCompositionLocals)
            set(materialized, SetModifier)
            set(compositeKeyHash, SetCompositeKeyHash)
        },
    )
}</code></pre>
</div>
<p><strong><code class="preserve-code-formatting">ReusableComposeNode</code> is no node in itself.</strong> What you see in the code above is no constructor call. It's instead just a call to yet another Composable. An apparently innocuous bit is the factory argument in line eight - even though it is very important. Because that's the function that <em>eventually</em> will create a node. It will create a <code class="preserve-code-formatting">ComposeUiNode</code>.</p>
<p>The <code class="preserve-code-formatting">ReusableComposeNode</code> Composable is highly tied to the Compose runtime. That's the code that tells the composer that a new group of type <code class="preserve-code-formatting">GroupKind.ReusableNode</code> should be started and then the code either creates a new node or reuses the existing one if we're recomposing. And finally it sets its content when the update function argument is used:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
@Composable
inline fun &lt;T : Any, reified E : Applier&gt; ReusableComposeNode(
    noinline factory: () -&gt; T,
    update: @DisallowComposableCalls Updater.() -&gt; Unit
) {
    if (currentComposer.applier !is E) invalidApplier()
    currentComposer.startReusableNode()
    if (currentComposer.inserting) {
        currentComposer.createNode(factory)
    } else {
        currentComposer.useNode()
    }
    Updater(currentComposer).update()
    currentComposer.endNode()
}</code></pre>
</div>
<p>We see that the factory gets passed on to the <code class="preserve-code-formatting">createNode()</code> call. This call schedules the node to be created when all insertions are processed. The compose runtime defers many things internally to allow for optimizations. Here we're not interested when this actually happens, suffice to say it <em>will</em> happen. And when it happens, the factory is going to be called.</p>
<p>Now let's look at the factory itself a bit closer: <code class="preserve-code-formatting">ComposeUiNode.Constructor</code> seems to be the constructor of the <code class="preserve-code-formatting">ComposeUiNode</code>. But that's once again not what it seems to be. Instead <code class="preserve-code-formatting">ComposeUiNode</code> is an interface that in itself doesn't do anything. It's actually the base interface used by <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/LayoutNode.kt"><code class="preserve-code-formatting">LayoutNode</code></a> - and the reason for this interface and this constructor method is given in the comment above the interface declaration:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="7"><code class="language-kotlin line-numbers">
/** Interface extracted from LayoutNode to not mark the whole LayoutNode class as @PublishedApi. */
@PublishedApi
internal interface ComposeUiNode {
    // ...
    /** Object of pre-allocated lambdas used to make use with ComposeNode allocation-less. */
    companion object {
        val Constructor: () -&gt; ComposeUiNode = LayoutNode.Constructor
        val VirtualConstructor: () -&gt; ComposeUiNode = { LayoutNode(isVirtual = true) }
        // ...
    }
}</code></pre>
</div>
<p><strong>So <code class="preserve-code-formatting">ComposeUiNode</code> is only an abstraction of <code class="preserve-code-formatting">LayoutNode</code>.</strong></p>
<h3 id="">LayoutNode</h3>
<p>In the section above we have seen when a <code class="preserve-code-formatting">LayoutNode</code> actually get's created. Basically whenever the <code class="preserve-code-formatting">Layout</code> composable is called. The <code class="preserve-code-formatting">LayoutNode</code> is the element in the tree that represents something on the screen. It needs to be measured, it might place children within its bounds and it might draw content.</p>
<p>Each <code class="preserve-code-formatting">LayoutNode</code> knows of its children and of its parent. So <code class="preserve-code-formatting">LayoutNodes</code> form a tree of nodes that represents the stuff that was emitted. To be clear: Compose creates a tree just like any other UI framework - but Google preferred to use some fancy naming for that. <strong>So whenever you hear/read about Composables emitting something, think about a LayoutNode getting created and inserted into the tree.</strong></p>
<p>The <code class="preserve-code-formatting">LayoutNode</code> class is actually pretty interesting and thus merits a blog post on it's own, where I will cover some aspects of it in more detail. </p>
<p>Two things are worth mentioning here:</p>
<ul>
<li>The <code class="preserve-code-formatting">Applier</code> is the instance that calls the respective tree handling methods of <code class="preserve-code-formatting">LayoutNode</code>.</li>
<li>The <code class="preserve-code-formatting">LayoutNode</code> holds a reference to an <code class="preserve-code-formatting">Owner</code>.</li>
</ul>
<p>I will cover both, the <code class="preserve-code-formatting">Applier</code> as well as the <code class="preserve-code-formatting">Owner</code> in separate blog posts since both are very important concepts when it comes to Compose.</p>
<h4>The purpose of a LayoutNode</h4>
<p><code class="preserve-code-formatting">LayoutNodes</code> form the UI tree and keep track of their parent node and child nodes. The management of the UI tree itself is done by the <code class="preserve-code-formatting">Applier</code>, which I will cover in another post. </p>
<p>And - also very important to keep in mind - the <code class="preserve-code-formatting">LayoutNode</code> gets stored in the <code class="preserve-code-formatting">SlotTable</code>.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_4');" onkeypress="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_4');" ><sup id="footnote_plugin_tooltip_4704_2_4" class="footnote_plugin_tooltip_text">4)</sup></a><span id="footnote_plugin_tooltip_text_4704_2_4" class="footnote_tooltip"></span></span> Thus when recomposing the runtime can reuse existing <code class="preserve-code-formatting">LayoutNodes</code> in case it decides that no change is required for this part of the tree.</p>
<p>The <code class="preserve-code-formatting">LayoutNode</code> also holds onto it's modifiers (see next section) and delegates to them to decide how much place is needed by this <code class="preserve-code-formatting">LayoutNode</code> (measuring), where to place stuff on the screen (layout) and finally what to show on the screen (drawing).</p>
<p>There's more to it - but as I mentioned that's part of another post.</p>
<h3 id="">Modifier.Node</h3>
<p>Modifiers are internally represented by <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier.Node"><code class="preserve-code-formatting">Modifier.Node</code></a> objects. <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier.Node">According to the doc</a> it is the "longer-lived object that is created for each Modifier.Element applied to a androidx.compose.ui.layout.Layout."</p>
<p>This "longer-lived" is interesting. Basically your <code class="preserve-code-formatting">Modifier.Node</code> lives for as long as it belongs to the modifier chain of a <code class="preserve-code-formatting">LayoutNode</code>. The <code class="preserve-code-formatting">LayoutNode</code> holds onto an object of type <a href="https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/node/NodeChain.kt"><code class="preserve-code-formatting">NodeChain</code></a> which keeps a list of modifiers internally and checks that, if this list is changed, the lifecycle methods of <code class="preserve-code-formatting">Modifier.Node</code> - like <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier.Node#onAttach()"><code class="preserve-code-formatting">onAttach()</code></a> etc. - are called.</p>
<p>There are many existing subtypes of <code class="preserve-code-formatting">Modifier.Node</code> - for example <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/node/LayoutModifierNode"><code class="preserve-code-formatting">LayoutModifierNode</code></a> (see below) or <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/node/DrawModifierNode?hl=en"><code class="preserve-code-formatting">DrawModifierNode</code></a>. The latter is responsible for actually drawing content on the screen, which I also plan to cover in a separate post.</p>
<p>Since <code class="preserve-code-formatting">LayoutNodes</code> are part of the <code class="preserve-code-formatting">SlotTable</code> the <code class="preserve-code-formatting">Modifier.Nodes</code> that are attached to a <code class="preserve-code-formatting">LayoutNode&#039;s</code> <code class="preserve-code-formatting">NodeChain</code> object obviously are part of that.</p>
<h4>A special subtype: <code class="preserve-code-formatting">LayoutModifierNode</code></h3>
<p><a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/node/LayoutModifierNode"><code class="preserve-code-formatting">LayoutModifierNodes</code></a> are the nodes that actually measure since they are the nodes that affect the size and placement on screen. As the documentation states: "A Modifier.Node that changes how its wrapped content is measured and laid out.". So whenever the chain of <code class="preserve-code-formatting">Modifier.Nodes</code> is traversed during measuring and laying out these nodes actually start the measuring.</p>
<p>Thus all modifiers that want to change the placement of their children or have any effect on the size of the overall Composable need to implement <code class="preserve-code-formatting">LayoutModifierNode</code>. One example for doing that is the <code class="preserve-code-formatting">SizeNode</code> which is the actual node used by modifiers like <code class="preserve-code-formatting">height()</code>, <code class="preserve-code-formatting">width()</code> or <code class="preserve-code-formatting">size()</code>.</p>
<h3 id="">SemanticsNode</h3>
<p>When you want to pass some information to the accessibility services of the device, you use the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#(androidx.compose.ui.Modifier).semantics(kotlin.Boolean,kotlin.Function1)"><code class="preserve-code-formatting">semantics</code></a> modifiers in Compose to tell the system which semantics properties to convey to the user.</p>
<p>But the accessibility services<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_5');" onkeypress="footnote_moveToReference_4704_2('footnote_plugin_reference_4704_2_5');" ><sup id="footnote_plugin_tooltip_4704_2_5" class="footnote_plugin_tooltip_text">5)</sup></a><span id="footnote_plugin_tooltip_text_4704_2_5" class="footnote_tooltip"></span></span> do not know of Compose. On other platforms that's obvious but given that Compose is backwards compatible (and on top of that not part of the deliverables of the Android framework), that's true on Android as well. </p>
<p>For accessibility the aforementioned <code class="preserve-code-formatting">Owner</code> comes again into place. It holds onto a <code class="preserve-code-formatting">SemanticsOwner</code> which acts as a bridge to the semantics framework of the respective platform.</p>
<p>To do so, the <code class="preserve-code-formatting">SemanticsOwner</code> holds onto a tree of <code class="preserve-code-formatting">SemanticNode</code> objects to describe the contents of the screen to users of accessibility services. Another thing I intend to cover in more detail in the future.</p>
<p>So stay tuned for more insights into Compose inner workings. Happy coding!</p>
<div class="speaker-mute footnotes_reference_container"> <div class="footnote_container_prepare"><p><span role="button" tabindex="0" class="footnote_reference_container_label pointer" onclick="footnote_expand_collapse_reference_container_4704_2();">Footnotes</span><span role="button" tabindex="0" class="footnote_reference_container_collapse_button" style="display: none;" onclick="footnote_expand_collapse_reference_container_4704_2();">[<a id="footnote_reference_container_collapse_button_4704_2">+</a>]</span></p></div> <div id="footnote_references_container_4704_2" style=""><table class="footnotes_table footnote-reference-container"><caption class="accessibility">Footnotes</caption> <tbody> 

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4704_2('footnote_plugin_tooltip_4704_2_1');"><a id="footnote_plugin_reference_4704_2_1" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>1</a></th> <td class="footnote_plugin_text">I use the term "side effects" in this paragraph as it has been used for ages in <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">computer science and functional programming</a>. I do not speak here about the <a href="https://developer.android.com/develop/ui/compose/side-effects">side effects</a> mentioned in the official Compose documentation. The Compose documentation at least in the past sometimes alluded to this use of side effects - though in actual fact Compose functions are anything but pure functions.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4704_2('footnote_plugin_tooltip_4704_2_2');"><a id="footnote_plugin_reference_4704_2_2" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>2</a></th> <td class="footnote_plugin_text">If you look at a Composable after the Compose Compiler plugin has done it's work, you will notice that it not only creates nodes, but that your function makes plenty of calls that change the global state of your app. But what they don't do, is drawing anything. At best they create draw operations that are recorded to be then called <em>at some point in the future</em>, when the system decides that the time for drawing has come. I will cover both topics, the drawing and the changes the compiler makes to your code, in two seperate posts in the future.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4704_2('footnote_plugin_tooltip_4704_2_3');"><a id="footnote_plugin_reference_4704_2_3" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>3</a></th> <td class="footnote_plugin_text">Actually, there are three Layout composables. But all three call <code class="preserve-code-formatting">ReusableComposeNode</code> down the road. The sample shown would be very similar for the other variants.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4704_2('footnote_plugin_tooltip_4704_2_4');"><a id="footnote_plugin_reference_4704_2_4" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>4</a></th> <td class="footnote_plugin_text">I most likely won't cover the SlotTable in this series. I recommend <a href="https://medium.com/androiddevelopers/under-the-hood-of-jetpack-compose-part-2-of-2-37b2c20c6cdd">this post about compose</a> by Richard Leland and also for how to use the slottable <a href="https://codingwithmohit.com/">Mohit Sarveiya's</a> <a href="https://www.youtube.com/watch?v=AWigEyb7xZg">videos about the SlotTable</a>.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4704_2('footnote_plugin_tooltip_4704_2_5');"><a id="footnote_plugin_reference_4704_2_5" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>5</a></th> <td class="footnote_plugin_text">The accessibility services on a device are AccessibilityService implementations on Android but different things on iOS the desktop or the web, thus I use the general term "accessibility services" in this post.</td></tr>

 </tbody> </table> </div></div><script type="text/javascript"> function footnote_expand_reference_container_4704_2() { jQuery('#footnote_references_container_4704_2').show(); jQuery('#footnote_reference_container_collapse_button_4704_2').text('−'); } function footnote_collapse_reference_container_4704_2() { jQuery('#footnote_references_container_4704_2').hide(); jQuery('#footnote_reference_container_collapse_button_4704_2').text('+'); } function footnote_expand_collapse_reference_container_4704_2() { if (jQuery('#footnote_references_container_4704_2').is(':hidden')) { footnote_expand_reference_container_4704_2(); } else { footnote_collapse_reference_container_4704_2(); } } function footnote_moveToReference_4704_2(p_str_TargetID) { footnote_expand_reference_container_4704_2(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } } function footnote_moveToAnchor_4704_2(p_str_TargetID) { footnote_expand_reference_container_4704_2(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } }</script><p>The post <a href="https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/">The Different Node Types in Jetpack Compose</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/the-different-node-types-in-jetpack-compose/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Why Google Limits APIs With Every Android Release: We Devs are to Blame!</title>
		<link>https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/</link>
					<comments>https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Wed, 20 Mar 2019 06:14:05 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<guid isPermaLink="false">https://www.grokkingandroid.com/?p=4203</guid>

					<description><![CDATA[<p>Last week Android Q was released. And the first thing that came to my mind when reading the Android Q announcement was: "Finer grained location permissions! Thats's great!" But then, it got me thinking: "Wait a moment! Why is this even necessary?" Don't get me wrong, I really think this addition is necessary and it [...]&#160;&#160;<a href="https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/">Continue Reading&#160;&#160;"Why Google Limits APIs With Every Android Release: We Devs are to Blame!"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/">Why Google Limits APIs With Every Android Release: We Devs are to Blame!</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Last week Android Q was released. And the first thing that came to my mind when reading the <a href="https://android-developers.googleblog.com/2019/03/introducing-android-q-beta.html">Android Q announcement</a> was: "Finer grained location permissions! Thats's great!" </p>
<p>But then, it got me thinking: "Wait a moment! Why is this even necessary?" </p>
<p>Don't get me wrong, I really think this addition <em>is</em> necessary and it is a big improvement. But...</p>
<p>Well, to be honest, this and similar changes are only necessary because we developers are not careful enough. We kill precious bandwidth or - in this case battery life - by being overly generous with the user's resources. Not to mention dealing with the user's privacy concerns in a haphazardly manner - if at all.</p>
<figure id="attachment_4238" aria-describedby="caption-attachment-4238" style="width: 700px" class="wp-caption aligncenter"><img decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/focus_on_privacy-700x500.png" alt="Privacy is at the core of Android Q" width="700" height="500" class="size-large wp-image-4238" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/focus_on_privacy-700x500.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/focus_on_privacy-500x357.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/focus_on_privacy-768x549.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/focus_on_privacy.png 884w" sizes="(max-width: 700px) 100vw, 700px" /><figcaption id="caption-attachment-4238" class="wp-caption-text">Privacy is at the core of Android Q</figcaption></figure>
<p>Alas, this disregard of the user's resources and privacy concerns is a theme we have had for quite a long time. And Google is trying to fix it, is trying to limit our ability to wreak havoc. This is a recurring theme to all the latest Android updates.</p>
<p>Notifications had to be reined in <a href="https://developer.android.com/about/versions/kitkat#44-beautiful-apps">again</a><span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_1');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_1');" ><sup id="footnote_plugin_tooltip_4203_4_1" class="footnote_plugin_tooltip_text">1)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_1" class="footnote_tooltip"></span></span> and <a href="https://developer.android.com/about/versions/lollipop#Notifications">again</a><span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_2');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_2');" ><sup id="footnote_plugin_tooltip_4203_4_2" class="footnote_plugin_tooltip_text">2)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_2" class="footnote_tooltip"></span></span> and <a href="https://developer.android.com/about/versions/nougat/android-7.0#notification_enhancements">again</a><span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_3');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_3');" ><sup id="footnote_plugin_tooltip_4203_4_3" class="footnote_plugin_tooltip_text">3)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_3" class="footnote_tooltip"></span></span> and <a href="https://developer.android.com/about/versions/oreo/android-8.0#notifications">again</a><span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_4');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_4');" ><sup id="footnote_plugin_tooltip_4203_4_4" class="footnote_plugin_tooltip_text">4)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_4" class="footnote_tooltip"></span></span> and <a href="https://developer.android.com/about/versions/pie/android-9.0#notifications">again</a><span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_5');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_5');" ><sup id="footnote_plugin_tooltip_4203_4_5" class="footnote_plugin_tooltip_text">5)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_5" class="footnote_tooltip"></span></span>. Honestly, we're really treating our users that badly.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_6');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_6');" ><sup id="footnote_plugin_tooltip_4203_4_6" class="footnote_plugin_tooltip_text">6)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_6" class="footnote_tooltip"></span></span> </p>
<p>And, yet, we still have notification spam. That's disgusting!<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_7');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_7');" ><sup id="footnote_plugin_tooltip_4203_4_7" class="footnote_plugin_tooltip_text">7)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_7" class="footnote_tooltip"></span></span> </p>
<figure id="attachment_4236" aria-describedby="caption-attachment-4236" style="width: 579px" class="wp-caption aligncenter"><img decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/notification_spam.png" alt="Notification Spam" width="579" height="210" class="size-full wp-image-4236" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/notification_spam.png 579w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2019/03/notification_spam-500x181.png 500w" sizes="(max-width: 579px) 100vw, 579px" /><figcaption id="caption-attachment-4236" class="wp-caption-text">Notification Spam</figcaption></figure>
<p>Same goes for the battery life. <a href="https://developer.android.com/about/versions/marshmallow/android-6.0-changes#behavior-power">Doze and App Standby</a>, <a href="https://developer.android.com/about/versions/nougat/android-7.0-changes#doze">later enhancements</a> to it as well as <a href="https://developer.android.com/about/versions/oreo/android-8.0-changes#back-all">background execution limits</a>: Only necessary because apps drained the battery and took bandwidth for granted. In short: because apps behaved as if users were only using this one app. </p>
<p>And why did apps behave that way? Because product managers wanted it that way. Because devs didn't care. Because someone intended to make a quick buck.</p>
<p>It's a pity that Google is being forced to go down that route. But I laud Google for doing so and am tremendously thankful for that. But it's a pity nonetheless.</p>
<p>It's not even optimal for users. For example settings concerning one app should be within the app. But since apps misused Android features too often, we have them scattered all over the place. Do you know off the top of your head where you can allow apps to draw on top of the screen?<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_8');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_8');" ><sup id="footnote_plugin_tooltip_4203_4_8" class="footnote_plugin_tooltip_text">8)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_8" class="footnote_tooltip"></span></span> Where to configure the notifications on your lock screen? Where to make another app the default SMS app?</p>
<p>In short: As a user I am glad that in Android Q I am able to limit background location access.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_9');" onkeypress="footnote_moveToReference_4203_4('footnote_plugin_reference_4203_4_9');" ><sup id="footnote_plugin_tooltip_4203_4_9" class="footnote_plugin_tooltip_text">9)</sup></a><span id="footnote_plugin_tooltip_text_4203_4_9" class="footnote_tooltip"></span></span> On the other hand I would have preferred if Google never would have been forced to do it that way in the first place.</p>
<p>It's not Google's fault. We devs are to blame. It's that simple. Time to do better, isn't it? improvements</p>
<div class="speaker-mute footnotes_reference_container"> <div class="footnote_container_prepare"><p><span role="button" tabindex="0" class="footnote_reference_container_label pointer" onclick="footnote_expand_collapse_reference_container_4203_4();">Footnotes</span><span role="button" tabindex="0" class="footnote_reference_container_collapse_button" style="display: none;" onclick="footnote_expand_collapse_reference_container_4203_4();">[<a id="footnote_reference_container_collapse_button_4203_4">+</a>]</span></p></div> <div id="footnote_references_container_4203_4" style=""><table class="footnotes_table footnote-reference-container"><caption class="accessibility">Footnotes</caption> <tbody> 

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_1');"><a id="footnote_plugin_reference_4203_4_1" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>1</a></th> <td class="footnote_plugin_text">Notification listeners allowed user's to control the appearance of notifications; AFAIK they were actually introduces with Jelly Bean - together with the per-app setting to disable notifications</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_2');"><a id="footnote_plugin_reference_4203_4_2" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>2</a></th> <td class="footnote_plugin_text">Lollipop's biggest notification reining in was the addition of the <a href="https://developer.android.com/reference/android/app/Notification.html#INTENT_CATEGORY_NOTIFICATION_PREFERENCES">Intent category for your settings activity</a> that controls the notifications settings. Of course the overall appearance changes and lockscreen settings were the more obvious changes.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_3');"><a id="footnote_plugin_reference_4203_4_3" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>3</a></th> <td class="footnote_plugin_text">Nougat added bundled notification - and bundled notifications even if devs didn't care about it.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_4');"><a id="footnote_plugin_reference_4203_4_4" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>4</a></th> <td class="footnote_plugin_text">Notification channels moved notification settings completely out of the app and allowed users to finetune the settings for each channel.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_5');"><a id="footnote_plugin_reference_4203_4_5" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>5</a></th> <td class="footnote_plugin_text">With Android Pie users could block groups of channels easily.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_6');"><a id="footnote_plugin_reference_4203_4_6" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>6</a></th> <td class="footnote_plugin_text">And I didn't even mention, that Android nowadays suggest to no longer deliver certain notifications if you swipe them away all the time.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_7');"><a id="footnote_plugin_reference_4203_4_7" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>7</a></th> <td class="footnote_plugin_text">Juhani Lehtimäki - rightfully appalled - <a href="https://twitter.com/lehtimaeki/status/1107930987399385090">posted about this abonimation on Twitter on March, 19th</a>.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_8');"><a id="footnote_plugin_reference_4203_4_8" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>8</a></th> <td class="footnote_plugin_text">One feature <a href="https://www.androidpolice.com/2019/03/16/android-q-steps-up-the-fight-up-against-overlay-based-malware/">on the verge of being limited too much</a> in Android Q in my opinion - if it stays that way.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4203_4('footnote_plugin_tooltip_4203_4_9');"><a id="footnote_plugin_reference_4203_4_9" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>9</a></th> <td class="footnote_plugin_text">Joe Birch has written a nice <a href="https://joebirch.co/2019/03/18/exploring-android-q-location-permissions/">summary about what those location permission changes mean for us devs</a>.</td></tr>

 </tbody> </table> </div></div><script type="text/javascript"> function footnote_expand_reference_container_4203_4() { jQuery('#footnote_references_container_4203_4').show(); jQuery('#footnote_reference_container_collapse_button_4203_4').text('−'); } function footnote_collapse_reference_container_4203_4() { jQuery('#footnote_references_container_4203_4').hide(); jQuery('#footnote_reference_container_collapse_button_4203_4').text('+'); } function footnote_expand_collapse_reference_container_4203_4() { if (jQuery('#footnote_references_container_4203_4').is(':hidden')) { footnote_expand_reference_container_4203_4(); } else { footnote_collapse_reference_container_4203_4(); } } function footnote_moveToReference_4203_4(p_str_TargetID) { footnote_expand_reference_container_4203_4(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } } function footnote_moveToAnchor_4203_4(p_str_TargetID) { footnote_expand_reference_container_4203_4(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } }</script><p>The post <a href="https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/">Why Google Limits APIs With Every Android Release: We Devs are to Blame!</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/google-stricter-with-android-releases-due-to-us-devs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Creating Kotlin DSLs</title>
		<link>https://www.grokkingandroid.com/creating-kotlin-dsls/</link>
					<comments>https://www.grokkingandroid.com/creating-kotlin-dsls/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Sat, 29 Dec 2018 03:05:09 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[Kotlin]]></category>
		<guid isPermaLink="false">https://www.grokkingandroid.com/?p=4096</guid>

					<description><![CDATA[<p>Kotlin has many nice things going for it - be it null safety, data classes, extension functions, immutable collections or many other things. For me one additional thing is very interesting: The ability to create domain specific languages (DSLs) easily. Easily, because creating a DSL with Kotlin means that you simply choose to combine several [...]&#160;&#160;<a href="https://www.grokkingandroid.com/creating-kotlin-dsls/">Continue Reading&#160;&#160;"Creating Kotlin DSLs"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/creating-kotlin-dsls/">Creating Kotlin DSLs</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Kotlin has many nice things going for it - be it null safety, data classes, extension functions, immutable collections or many other things. For me one additional thing is very interesting: The ability to create domain specific languages (DSLs) easily. Easily, because creating a DSL with Kotlin means that you simply choose to combine several core features of the language.</p>
<figure id="attachment_4193" aria-describedby="caption-attachment-4193" style="width: 700px" class="wp-caption aligncenter"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/12/dsl_sample-700x337.png" alt="A DSL sample" width="700" height="337" class="size-large wp-image-4193" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/12/dsl_sample-700x337.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/12/dsl_sample-500x241.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/12/dsl_sample-768x370.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/12/dsl_sample.png 1258w" sizes="auto, (max-width: 700px) 100vw, 700px" /><figcaption id="caption-attachment-4193" class="wp-caption-text">A DSL sample</figcaption></figure>
<h3>What is a DSL</h3>
<p>But first things first: What actually is a domain specific language?</p>
<p>A domain specific language is a construct that allows you to create things and set them up in a way that feels more natural and usually comes closer to proper language usage than normal code.</p>
<p>As the name implies, DSLs are only useful in a constrained context - the domain at hand. In contrast to general purpose languages (of which Kotlin of course is one) DSLs apply to a limited set of use cases only.</p>
<p>What then is the benefit of using a DSL over normal constructs? The main benefit is, that domain specific languages provide a more concise and at the same time much better readable API for a specific purpose, compared to the normal general purpose way to achieve the same.</p>
<h4>External DSLs</h4>
<p>DSLs are nothing new actually. They have been available in other languages for quite a while (on the JVM for example in Groovy and Scala). Actually most DSLs are language independent. Famous examples are SQL, HTML, Gherkin or all those YAML files that are all the rage nowadays.</p>
<p>You can write code using those DSLs in any text editor and later the DSL is then used and parsed by some other code. For example a RDBMS parses SQL, Cucumber parses your Gherkin code, a browser the HTML code and so on. In theory a parser for this could be written in any language. The DSL is external to the language with which it is parsed. Those DSLs are external DSLs. Frederico Tomassetti has compiled a list of more <a href="https://tomassetti.me/domain-specific-languages/">examples of these</a>.</p>
<h4>Internal DSLs</h4>
<p>But there are also internal DSLs. They are written in the same general purpose language as the DSL itself. The DSL is just a specific way to use the host language. Gradle is an example of an internal DSL - in this case in Groovy.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_1');" onkeypress="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_1');" ><sup id="footnote_plugin_tooltip_4096_6_1" class="footnote_plugin_tooltip_text">1)</sup></a><span id="footnote_plugin_tooltip_text_4096_6_1" class="footnote_tooltip"></span></span></p>
<p>When I’m speaking of Kotlin DSLs, I’m speaking of internal DSLs, of DSLs that make use of specific Kotlin features to achieve their simplicity and benefits.</p>
<h3>Examples of Kotlin DSLs</h3>
<p>Let’s see some examples of DSLs with Kotlin to show what DSLs are about and why I like them.</p>
<h4>KotlinTest</h4>
<p><a href="https://github.com/kotlintest/kotlintest">KotlinTest</a> is a library to write better unit tests. One benefit of KotlinTest is the way it allows you to structure your test code as you can see in the following sample:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
"when user entered credentials" {
    "and clicked the login button" {
        "and the credentials were valid, then the app" {
            should("switch to main flow") {
                // testing logic goes here :-)
            }
            // more should blocks ...
        }
        // more contexts ...
    }
}</code></pre>
</div>
<p>Having done quite some work with Javascript (mostly for the Google Assistant), I started to like <a href="https://jasmine.github.io/">Jasmine</a> and gripe about what I used to use on the JVM. Happily with KotlinTest better structured and more easily readable tests for Kotlin projects are no longer an issue.</p>
<h4>Anko</h4>
<p>I think the Kotlin DSL most well known among Android developers is <a href="https://github.com/Kotlin/anko">Anko</a>, especially Anko layouts. If you like to write layouts in code (like in Flutter or React) this can be pretty interesting for you.</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="3-8"><code class="language-kotlin line-numbers">
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    verticalLayout {
        val name = editText()
        button("Say Hello") {
            onClick { toast("Hello, ${name.text}!") }
        }
    }
}</code></pre>
</div>
<p>I personally happen to prefer the XML way for layouts and as such am no Anko user. But it’s a well liked project with 13.000 stars on github, so I might be an outlier when it comes to that.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_2');" onkeypress="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_2');" ><sup id="footnote_plugin_tooltip_4096_6_2" class="footnote_plugin_tooltip_text">2)</sup></a><span id="footnote_plugin_tooltip_text_4096_6_2" class="footnote_tooltip"></span></span></p>
<h4>Koin</h4>
<p>The final example to show the value of DSLs is <a href="https://insert-koin.io/">Koin</a>. Koin is a dependency injection framework <span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_3');" onkeypress="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_3');" ><sup id="footnote_plugin_tooltip_4096_6_3" class="footnote_plugin_tooltip_text">3)</sup></a><span id="footnote_plugin_tooltip_text_4096_6_3" class="footnote_tooltip"></span></span> specific for Kotlin. And it integrates nicely with Android (though it works on standalone JVM projects as well).</p>
<p>Since Koin 2.0 will be even better than the current version, I use samples of the upcoming version. It’s going to be released soon enough for this blog to highlight Koin 2.0.</p>
<p>With Koin you define your dependencies like this:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
val appModule = module {
    single { AndroidLogger() as Logger }
    single(name = "mainDispatcher") { Dispatchers.Main as CoroutineDispatcher }
    //...
}
// and somewhere else:
koinApplication {
    useAndroidContext(this@SomeApp)
    loadModules(appModule, loginModule, ...)
}</code></pre>
</div>
<p>Again the important thing is, that you can understand easily what is going on here.</p>
<p>There are of course many more examples. Actually DSLs can enhance and ease the use of many libraries, so I expect them to pop up more and more.</p>
<p>But what is common to all these and other samples, is that DSLs are nicely readable. They make the intent of the code obvious and as such they help us achieve understandability and maintainability of our code. That's why I like DSLs - if appropriately designed and judiciously used <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Creating your own DSL</h3>
<p>Now that we’ve seen sample of DSLs, let’s cover how to actually create one. I will go through some more snippets of code from the many libraries that already offer DSLs and show how they made use of simple Kotlin concepts to achieve the desired result.</p>
<h4>Designing a DSL</h4>
<p>A DSL is part of your public API that you expose to clients. And since DSLs are part of the overall API, you should also follow common design approaches for APIs.</p>
<p>The first design consideration is, that you always should design with the client usage on your mind. It’s not your job to make the creation of your DSL easy for <em>you</em>. It’s your job to make the <em>usage</em> of your DSL as easy and as intuitive as possible for your <em>client</em>.</p>
<p>The overall guiding principle is, that the proper use of your API should be easy, while any potential misuse should be as hard to make as possible. This is one of the many advices by Joshua Bloch in his <a href="https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/32713.pdf">presentation on the topic of API design</a>. This one recommendation is probably the most important one, but I strongly recommend to have a look at all of his slides.</p>
<p>One way to ease client development is to shield the client from any technical obstacles. Do not hassle the client with technical details that are of no importance to her.</p>
<p>But what to do if your client might be interested in them. For example information about what went wrong when trying to do a remote call. In that case you could offer a reasonable default behavior for all those that do not care about the details and only make those details available to those clients that want to act differently depending on the cause of the problem.</p>
<p>A DSL specific part of API design is the proper naming of things and of choosing a good syntax. When it comes to naming things, solutions should be kind of obvious. After all you are creating a <em>domain</em> specific language. And as such you should follow the naming conventions of the domain at hand. There also might exist established patterns for naming entities or actions on them. If so, you should follow along to meet client expectations.</p>
<p>With these thoughts in mind you can start designing your DSL. The following paragraphs concentrate on the various elements of the Kotlin language that can help you achieve a nice DSL.</p>
<h4>Trailing lambdas</h4>
<p>Let’s start with trailing lambdas since they are so common in Kotlin, that you are bound to have seen them.</p>
<p>A trailing lambda is simply syntactic sugar for using function types as arguments to your higher order functions. For example the way you use the should spec style in KotlinTest is made possible by using trailing lambdas. This is a simplified should spec function:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="1,6"><code class="language-kotlin line-numbers">
should("show an error message when something bad happened") {
    presenter.doSomething()
    verify {
        view.showError("Some error")
    }
}</code></pre>
</div>
<p>And this is how the <code class="preserve-code-formatting">should</code> method is defined in the KotlinTest code base:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
fun should(name: String, test: () -&gt; Unit): TestCase {
    val testCase = TestCase(
            suite = current, name = "should $name", test = test, config = defaultTestCaseConfig)
    current.addTestCase(testCase)
    return testCase
}</code></pre>
</div>
<p>As you can see, the argument list of this function expects another function as the last argument, the <code class="preserve-code-formatting">test</code> argument. And the language designers of Kotlin made it possible to simplify passing the lambdas in when they are the last argument by allowing you to close the argument parenthesis before starting the lambda. </p>
<p><strong>Without</strong> trailing lambdas, the should spec above would have looked like that:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="1,6"><code class="language-kotlin line-numbers">
should("show an error message when something bad happened", {
    presenter.doSomething()
    verify {
        view.showError("Some error")
    }
})</code></pre>
</div>
<p>This is, of course, valid code, but the placements of the parentheses doesn’t look that nice. By allowing you to put the closing parenthesis in front of the lambda argument, the code becomes more readable.</p>
<h4>Extension functions</h4>
<p>Extension functions are a common pattern that is widely used in existing Kotlin DSLs. They allow you to extend existing classes and to make those extensions only valid within the scope of your DSL.</p>
<p>The next code snippet shows how to write an extension function for the String class. It simply returns a new String in which the original characters are turned into dots. Think of replacing clear text passwords in logs and so on.</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
fun String.toDots() =
        this.replace(".".toRegex(), "●")</code></pre>
</div>
<p>In the Spring routing DSL extension functions on Strings are used to specify handlers for certain paths, to nest different parts of the path or to combine a path with another request predicate. For example to combine a path with the requirement for a certain content type you can use this code:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
("/api" and contentType(MediaType.APPLICATION_JSON)) { 
    userHandler.findAll(it) 
}</code></pre>
</div>
<p>In this case the <code class="preserve-code-formatting">and</code> is an extension function on String:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other)</code></pre>
</div>
<p>We will cover the <code class="preserve-code-formatting">infix</code> part pretty soon. For now we concentrate on the fact that by providing this extension function, the routing DSL allows us to write code that is readable and quickly understandable.</p>
<p>If you come from Java, you might wonder about this, since <code class="preserve-code-formatting">String</code> is final and you cannot inherited from it. That’s true, and you still would be able to write extension functions for Java’s <code class="preserve-code-formatting">String</code> class.</p>
<p>That’s working since the Kotlin compiler transforms extension functions into static functions that take the object in question, in this case the string, as an additional first parameter. As such the code is not really extending the <code class="preserve-code-formatting">String</code> class, it’s just pretending to do so.</p>
<h4>Infix calls</h4>
<p>Now the sample just used was still a bit weird since it didn’t look like a normal function call. That’s because the <code class="preserve-code-formatting">and</code> function is an <em>infix</em> function, denoted by the <code class="preserve-code-formatting">infix</code> keyword.</p>
<p>Infix functions are functions with exactly one parameter and the infix keyword makes it possible to separate the object and it’s single parameter by the function name. Which is ideal for DSLs since it makes your code more naturally readable.</p>
<p>Instead of having to write the call <code class="preserve-code-formatting">“somePath”.and(somePredicate)</code> you are able to use <code class="preserve-code-formatting">&quot;somePath&quot; and somePredicate</code> instead. Much better.</p>
<p>Another sample for infix calls is the following code:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
every { view.showNewState(any()) } just runs</code></pre>
</div>
<p>The <code class="preserve-code-formatting">just</code> method tells MockK that a code, that doesn't return any value, must nevertheless run at least once when calling the object under test.</p>
<p>The way to write it like shown above, is only possible because of the use of the <code class="preserve-code-formatting">infix</code> keyword:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
infix fun MockKStubScope.just(runs: Runs) 
        = answers(ConstantAnswer(Unit))</code></pre>
</div>
<p>Without the infix keyword one would have to write the MockK definition like this:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
every { view.showNewState(any()) }.just(runs)</code></pre>
</div>
<p>So we would have to add the dot between the object and it's function and we would have to put the argument within parentheses. I guess you agree that the version that actually uses the infix syntax is much easier to read.</p>
<h4>Empty objects</h4>
<p>Now let’s have another look at the MockK sample we've just seen. This time we don’t look at the <code class="preserve-code-formatting">just</code> but at the <code class="preserve-code-formatting">runs</code>. What is that actually.</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
every { view.showNewState(any()) } just runs</code></pre>
</div>
<p>It turns out that it is an empty object:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
object Runs
typealias runs = Runs</code></pre>
</div>
<p>An object without any behaviour that exists only to make this infix syntax possible at all.</p>
<p>Now, be careful with this and don’t overdo it. Very often other ways might be better. In this case, though, I like it.</p>
<h4>Conventions</h4>
<p>You have already seen how extension functions as well as trailing lambdas can help you when writing a DSL, but the following code still looks a bit weird:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
"should show an error message when something bad happened" {
    presenter.doSomething()
    verify {
        view.showError("Some error")
    }
}</code></pre>
</div>
<p>It is nearly the same test method you have seen a few paragraphs before, but now instead of using the should spec style it's using a string spec style. </p>
<p>This code snippet suggests that you can pass a lambda to an object. As if the object were a function itself. But of course it is not <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<p>There is a convention in Kotlin, though, that allows you to treat objects as if they <em>were</em> functions. At least in some very restricted context. </p>
<p>If the object in question has a method named <code class="preserve-code-formatting">invoke</code> and this function acts as a higher-order funtion, that accepts a function as argument, you can call it like shown above.</p>
<p>A look at the definition of this method makes it easier to understand:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="1"><code class="language-kotlin line-numbers">
operator fun String.invoke(test: () -&gt; Unit): TestCase {
    val tc = TestCase(suite = rootTestSuite, name = this, test = test, config = defaultTestCaseConfig)
    rootTestSuite.addTestCase(tc)
    return tc
}</code></pre>
</div>
<p>You can have multiple <code class="preserve-code-formatting">invoke</code> methods. And you can use them as extension functions to enhance existing classes, like the <code class="preserve-code-formatting">String</code> class in this sample.</p>
<h4>Lambdas with receivers</h4>
<p>You have already seen what trailing lambdas are. But in many cases a normal lambda is not enough. Since DSLs are especially useful for creating and setting up objects or even fully fledged object graphs, we need a way to do exactly that. This is where lambdas with receivers (or <a href="https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver">function literals with receivers</a>) enter the scene. They allow a domain specific language to create a specific object for you while expecting the configuration of that object in the trailing lambda. But how?</p>
<p>Let's see an example first:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
val appModule = module {
    single { AndroidLogger() as Logger }
    single(name = "mainDispatcher") { Dispatchers.Main as CoroutineDispatcher }
    //...
}</code></pre>
</div>
<p>What you see here is the Koin 2.0 way to initialize the module graph. Nowhere in this code do you actually create module objects. So the methods must do that for you. </p>
<p>The same mechanism is also what allows Anko to create the view hierarchy for your screens. Let's review the code shown initially in the DSL sample section:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
verticalLayout {
    val name = editText()
    button("Say Hello") {
        onClick { toast("Hello, ${name.text}!") }
    }
}</code></pre>
</div>
<p>The <code class="preserve-code-formatting">verticallayout</code> and <code class="preserve-code-formatting">button</code> blocks are where objects get created and in the respective trailing lambdas you define how to set up those objects.</p>
<p>Within the lambdas you have access to the newly created object as this and thus there is no implicit argument named <code class="preserve-code-formatting">it</code>.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_4');" onkeypress="footnote_moveToReference_4096_6('footnote_plugin_reference_4096_6_4');" ><sup id="footnote_plugin_tooltip_4096_6_4" class="footnote_plugin_tooltip_text">4)</sup></a><span id="footnote_plugin_tooltip_text_4096_6_4" class="footnote_tooltip"></span></span></p>
<p>Now let's see how a trailing lambda looks like from the perspective of the DSL creator. The above <code class="preserve-code-formatting">modules</code> method definition looks like this:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="1,4"><code class="language-kotlin line-numbers">
typealias ModuleDeclaration = Module.() -&gt; Unit

fun module(createdAtStart: Boolean = false, override: Boolean = false, moduleDeclaration: ModuleDeclaration): Module {
    return Module(createdAtStart, override).apply(moduleDeclaration)
}</code></pre>
</div>
<p>You can think of function literals with receivers as of local extension functions that are valid only within the scope of the defining function. </p>
<p>As you can see in above's typealias the function type is an extension function on <code class="preserve-code-formatting">Module</code>. The only thing missing from a normal extension function definition is the name of the function. And this is exactly the same as the name of the argument. So in this case <code class="preserve-code-formatting">moduleDeclaration</code> (the last argument to the <code class="preserve-code-formatting">module</code> function on line 3).</p>
<p>On line 4 the function type that was passed into the <code class="preserve-code-formatting">module</code> function is then passed on to the <code class="preserve-code-formatting">apply</code> function. But the <code class="preserve-code-formatting">Module</code> object itself, on which the local extension function is defined, is not passed into the function. Instead it is created within the function right after the <code class="preserve-code-formatting">return</code> keyword.</p>
<p>Lambdas with receivers might be hard to grasp initially. But they are an important Kotlin concept - not only within the context of DSLs. You can read more about <a href="https://kotlinexpertise.com/function-literals-with-receiver/">function literals with receivers</a> on Simon Wirtz' blog.</p>
<h4>DSLMarker</h4>
<p>If you have lambdas with receivers the lambda can access the receiving object with this. But if you have nested structures this can apply to many objects in the hierarchy. And using a method on an object might be wrong outside of the given scope.</p>
<p>That's where the DSLMarker annotation comes into play. If you have multiple annotations the function closest to the call wins. Thus, given the Anko sample above, any methods specific to <code class="preserve-code-formatting">verticallayout</code> are not accessible within the trailing lambda of the <code class="preserve-code-formatting">button</code>.</p>
<p>This is great in preventing accidental misuse of your DSL. As you might recall, making your API hard to misuse is one of the fundamental aspects of API design. Luckily Kotlin has us covered!</p>
<p>Let's see it in action in Anko:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="1,9"><code class="language-kotlin line-numbers">
inline fun ViewManager.button(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.Button).() -&gt; Unit): android.widget.Button {
    return ankoView(`$$Anko$Factories$Sdk25View`.BUTTON, theme = 0) {
        init()
        setText(text)
    }
}
//... somewhere else:
inline fun Activity.verticalLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -&gt; Unit): LinearLayout {
    return ankoView(`$$Anko$Factories$CustomViews`.VERTICAL_LAYOUT_FACTORY, theme, init)
}</code></pre>
</div>
<p>And here's the definition of the annotation:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers"><code class="language-kotlin line-numbers">
@DslMarker
@Target(AnnotationTarget.TYPE)
annotation class AnkoViewDslMarker</code></pre>
</div>
<h4>What also might help your DSL</h4>
<p>Kotlin allows you to define <strong>type aliases</strong>, which are a nice way to make your code more explicit. In the MockK example you have seen a type alias for the object <code class="preserve-code-formatting">Runs</code> which made it possible to use the word in a more natural way.</p>
<p>Another thing to consider is <strong>operator overloading</strong>. Actually <code class="preserve-code-formatting">invoke</code> - shown above - is an operator. But there might be others that can come in handy, for example <code class="preserve-code-formatting">plus</code> or <code class="preserve-code-formatting">unaryPlus</code>. The library <a href="https://github.com/Kotlin/kotlinx.html">kotlinx.html</a> for example makes use of the <code class="preserve-code-formatting">unaryPlus</code> operator:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers" data-line="4"><code class="language-markup line-numbers">
html {
    body {
        div {
            +"a trivial example"
        }
    }
}</code></pre>
</div>
<p>Finally I recommend to consider <strong>deviating from naming conventions</strong>. The <a href="https://docs.spring.io/spring-framework/docs/5.0.11.RELEASE/kdoc-api/spring-framework/org.springframework.web.reactive.function.server/-router-function-dsl/">routing DSL in Spring</a> for example uses methods to route incoming traffic to certain handler methods. And since they are dealing with HTTP verbs they name those methods in all upper case like GET, PUT, POST and so on. I think in this case the deviation from normal naming conventions is justified and makes the intent of the code more obvious than if the methods were in lower case:</p>
<div class="sourcecode">
<pre class="language-kotlin line-numbers" data-line="3"><code class="language-kotlin line-numbers">
"/api".nest {
    accept(APPLICATION_JSON).nest {
        GET("/users", userHandler::findAll)
    }
}</code></pre>
</div>
<p>You can find a more complete example for this in <a href="https://github.com/mixitconf/mixit/blob/master/src/main/kotlin/mixit/web/routes/ApiRoutes.kt">this gist</a>.</p>
<h3>Is it worth it?</h3>
<p>Now that you have seen how to create a DSL, you still have to consider whether to go for it. And again, there are two aspects to it:</p>
<ul>
<li>Should you use a DSL if one exists?</li>
<li>Should you create a DSL for your API?</li>
</ul>
<h4>Should you use a DSL?</h4>
<p>The answer whether to use one or not is pretty easy: of course you should. But, then again, it’s not that easy.</p>
<p>You might have to decide which library to use for a specific problem. And a DSL might help you choose one over the other. But, of course, it’s not the only thing to take into consideration when selecting a library. You still need to be sure that the API fulfills your overall needs, that it is likely to be maintained in the long run (or easy enough to fork and maintain yourself in case the original maintainer(s) wander off).</p>
<p>If two or more libraries fulfill your needs, are more or less equally likely to be maintained in the long run and have an overall nicely designed API I would choose the one that offers the best readability of the client code. If one of those libraries uses a DSL, it’s likely that this one is the lib whose client code is best to maintain and easiest to read. In such a case, a DSL can be the reason to choose one library over the other.</p>
<h4>Should you create a DSL?</h4>
<p>As nice as a DSL might be, it still comes at a cost. It’s simply more costly to create one. While any API has to be designed carefully, a DSL puts some extra workload on your shoulders. Thus you have to ask yourself whether you should go for it or not.</p>
<p>This depends largely on what your use case is. Is your API for inhouse clients? Is your API used very often or only every now and then?</p>
<p>For libraries things are a tad different. Here the most important questions to ask yourself is: Does your client really benefit of a DSL? Does the domain in question lend itself easily to a DSL and does it offer enough and intuitive concepts to create one? If so, you probably should create one. It will help your library gain traction over those, that do not provide one.</p>
<p>This is even true for Java based libraries. Consider to offer special constructs for Kotlin. The people at Pivotal did so while creating Spring 5. They offer a DSL for Kotlin users even though most of the overall Spring code is written in Java. For me this was one big selling point when considering which Java lib to use for my latest App backend.</p>
<p>It all boils down to this: Is the client code easier to read and write if you provide a DSL?</p>
<p>If yes, by all means go for it. And if not, it’s just not worth it.</p>
<p>But even if you decide <em>not</em> to create a DSL, all the things above might still help you create a nicely designed API that is easy to use. Especially trailing lambdas and function literals with receivers are a very common pattern in Kotlin that might be a good fit for your API - DSL or not.</p>
<h3>When’s a DSL a DSL?</h3>
<p>By now you hopefully are convinced that DSLs make code more readable and can be worth the effort. You really want to create one, but you’re not sure, if what you’re thinking about is actually a DSL or not. Actually that’s a very tough question, since there are not hard and fast rules that make some code a DSL and some other code not.</p>
<p>In my opinion it all boils down to the question whether the domain offers enough concepts to actually create a meaningful DSL out of it. And if you can create a proper language out of the concepts. After all it’s no DSL if either the domain or the language part of it are missing.</p>
<p>In the end it doesn’t really matter that much. Because the important thing is, that your overall API is easy to use. Whether it’s a proper DSL or just a nicely designed API is not important. Important is, that your API takes the general recommendations for good API design into consideration. That it takes the client front and center while designing the API and that it thus makes the use of your API intuitive and easy and the misuse hard: That’s the problem you have to tackle. And if you do so, your client’s will like to use your API and the resulting code will be easy to maintain.</p>
<h3>Want to know more?</h3>
<p>There are <a href="https://kotlinexpertise.com/create-dsl-with-kotlin/">some</a> <a href="https://proandroiddev.com/writing-dsls-in-kotlin-part-1-7f5d2193f277">good</a> <a href="https://www.cuba-platform.com/blog/kotlin-dsl-from-theory-to-practice">blog</a> posts and some information on the <a href="https://kotlinlang.org/docs/reference/type-safe-builders.html">Kotlin website</a> that also cover Kotlin DSLs.</p>
<p>In addition to that I highly recommend reading the book <a href="https://www.manning.com/books/kotlin-in-action">Kotlin in Action</a>. This book is outstanding - and it has a chapter on DSLs. It might be worth to check if it's available as a deal on Mannings site in their <a href="https://www.manning.com/news/countdown-to-2019">year's end sale</a>.</p>
<p>It's always important not to go overboard with new features. That's why in my talks about Kotlin DSLs I always recommend having a look at <a href="https://github.com/zsmb13/VillageDSL">Márton Braun's repo</a> that discusses the pros and cons of different approaches and provides sample code for all of them. He has nicely summarized the <a href="https://zsmb.co/kotlin-dsl-design-with-village-dsl/">different DSL styles</a>.</p>
<p>Happy coding!</p>
<div class="speaker-mute footnotes_reference_container"> <div class="footnote_container_prepare"><p><span role="button" tabindex="0" class="footnote_reference_container_label pointer" onclick="footnote_expand_collapse_reference_container_4096_6();">Footnotes</span><span role="button" tabindex="0" class="footnote_reference_container_collapse_button" style="display: none;" onclick="footnote_expand_collapse_reference_container_4096_6();">[<a id="footnote_reference_container_collapse_button_4096_6">+</a>]</span></p></div> <div id="footnote_references_container_4096_6" style=""><table class="footnotes_table footnote-reference-container"><caption class="accessibility">Footnotes</caption> <tbody> 

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4096_6('footnote_plugin_tooltip_4096_6_1');"><a id="footnote_plugin_reference_4096_6_1" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>1</a></th> <td class="footnote_plugin_text">The Groovy DSL is the default for gradle. But there’s also a Kotlin variant available.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4096_6('footnote_plugin_tooltip_4096_6_2');"><a id="footnote_plugin_reference_4096_6_2" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>2</a></th> <td class="footnote_plugin_text">Alas, Anko hasn't been ported to androidx as of yet (2018-12-28). Depending on Anko's update cycle can also be problematic if you want to use bleeding edge views (e.g. MotionLayout).</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4096_6('footnote_plugin_tooltip_4096_6_3');"><a id="footnote_plugin_reference_4096_6_3" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>3</a></th> <td class="footnote_plugin_text">Well, yes, <a href="https://twitter.com/jakewharton/status/908419644742098944">it’s not really</a>: It's a service locator. But what's important is, that it works pretty nicely and fulfills <em>my</em> needs. I just want you to be aware of the difference. For more listen to <a href="https://simplecast.com/s/e90120f8">this Fragmented podcast</a>.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_4096_6('footnote_plugin_tooltip_4096_6_4');"><a id="footnote_plugin_reference_4096_6_4" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>4</a></th> <td class="footnote_plugin_text">While common within DSLs it is of course not <em>necessary</em> to create the target objects within the called function. You can also use a lambda with receiver as an extension function on an object. That's for example what the standard Kotlin function <code class="preserve-code-formatting">apply</code> makes use of and why it is so useful for initializing objects.</td></tr>

 </tbody> </table> </div></div><script type="text/javascript"> function footnote_expand_reference_container_4096_6() { jQuery('#footnote_references_container_4096_6').show(); jQuery('#footnote_reference_container_collapse_button_4096_6').text('−'); } function footnote_collapse_reference_container_4096_6() { jQuery('#footnote_references_container_4096_6').hide(); jQuery('#footnote_reference_container_collapse_button_4096_6').text('+'); } function footnote_expand_collapse_reference_container_4096_6() { if (jQuery('#footnote_references_container_4096_6').is(':hidden')) { footnote_expand_reference_container_4096_6(); } else { footnote_collapse_reference_container_4096_6(); } } function footnote_moveToReference_4096_6(p_str_TargetID) { footnote_expand_reference_container_4096_6(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } } function footnote_moveToAnchor_4096_6(p_str_TargetID) { footnote_expand_reference_container_4096_6(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } }</script><p>The post <a href="https://www.grokkingandroid.com/creating-kotlin-dsls/">Creating Kotlin DSLs</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/creating-kotlin-dsls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Those &#8220;mobile apps are doomed&#8221; headlines? They are wrong!</title>
		<link>https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/</link>
					<comments>https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 27 Feb 2018 09:11:55 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<guid isPermaLink="false">https://www.grokkingandroid.com/?p=4041</guid>

					<description><![CDATA[<p>So lately there are a lot of headlines appearing that say "Businesses Moving To Chatbots, AI; Away From Mobile Apps", "The Rise of Chatbots - Why they’ll replace All Your Apps!" or "How Bots Will Completely Kill Websites and Mobile Apps". First of all: Look at where those headlines appear. Some of these websites - [...]&#160;&#160;<a href="https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/">Continue Reading&#160;&#160;"Those &#8220;mobile apps are doomed&#8221; headlines? They are wrong!"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/">Those &#8220;mobile apps are doomed&#8221; headlines? They are wrong!</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So lately there are a lot of headlines appearing that say "<a href="https://www.mediapost.com/publications/article/315146/businesses-moving-to-chatbots-ai-away-from-mobil.html">Businesses Moving To Chatbots, AI; Away From Mobile Apps</a>", "<a href="https://www.techechelons.com/blog/the-rise-of-chatbots-why-they-ll-replace-all-your-apps">The Rise of Chatbots - Why they’ll replace All Your Apps!</a>" or "<a href="https://chatbotsmagazine.com/how-bots-will-completely-kill-websites-and-mobile-apps-656db8e6fc03">How Bots Will Completely Kill Websites and Mobile Apps</a>". First of all: Look at where those headlines appear. Some of these websites - though not all - have a vested interest in making you believe that.</p>
<p>Speaking of where those posts appear: Isn't it funny that the last post appears on a <em>website</em>? Why not use a bot to tout the message? Maybe not so appropriate after all?</p>
<p>Well, so what to make of these post? Are they just trying to convince customers to buy services? Or is there actually something to it?</p>
<p style="text-align: center">
<img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/02/doomsday-1-700x204.png" alt="" width="700" height="204" class="aligncenter size-large wp-image-4066" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/02/doomsday-1-700x204.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/02/doomsday-1-500x146.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/02/doomsday-1-768x224.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2018/02/doomsday-1.png 1200w" sizes="auto, (max-width: 700px) 100vw, 700px" />
</p>
<p>I believe that there is indeed <em>some</em> truth to voice assistants and chatbots replacing apps. But the overall message is simply wrong. It's more a co-existance of both for a very long future. And they are also not mutually exclusive. Assistant integration into apps or chatbots on websites? Why not? We see this all the time.</p>
<p>Yes, sometimes voice assistants or chatbots <em>are</em> the best way to fulfill a user's need. Sometimes they are not there <em>yet</em>, but you know that they will be soon.</p>
<p>I for one use Google Home more and more to listen to music (mostly streaming to my Chromecast Audio). But I think the Play Music app is much better <em>right now</em>. Do I expect it to stay that way? No. I expect the Play Music app to play an ever lesser role for my music listening experience. </p>
<p>Do I expect the Play Music app to be replaced completely anytime soon? No, I don't. Sometimes I use it on my laptop. Sometimes on my phone, sometimes I stream from there via Chromecast Audio. It depends on where I am and what I am doing right now. Do I expect it to be replaced entirely eventually. Sure: By <em>something</em> else. But that's true for nearly everything. Nothing stays forever. Luckily so!</p>
<p>Now these doomsaying headlines have been around for ages. Though mostly applied to other technologies. Sometimes they are true (as for Kodak for example), but very often they are not. Especially in the media world.</p>
<p>When Radio was announced, it was deemed to be the end for newspapers. Not so. Radio was said to be doomed by TV. Not so. Movie theaters were obviously doomed by downloads. Not so. TV then again was said to be doomed by apps and youtube. Not so. Or just: not so <em>yet</em>? </p>
<p>Even after all those years, the radio is still around. TV is still around. Same goes for PCs and laptops. Heck: Even newspapers and paper books are still around - though I personally think they actually might be doomed, as much as I like them. </p>
<p>All of these still serve a need and are best suited in <em>some</em> cases. But neither of these technologies plays as much of an role as it has been playing in its heydays. And <em>that</em> probably is going to happen to mobile apps - and eventually also to the phones and tablets that run them.</p>
<p>Neither expected them to stay around forever. But for lots of use cases they are definitely still the best choice and will stay that way until something better comes around. For many use cases neither chatbots nor voice apps are a good choice. </p>
<p>BTW: For lots of use cases neither mobiles nor tablets are a good choice - which is why we still use laptops (including me typing this post). So laptops will stay around for some time - but admittedly have lost out for some users. That <em>might</em> happen to apps.</p>
<p>And, of course, for some use cases voice assistants or chatbots are indeed better. For some it depends on the specific need of the user and the specific circumstance the user is in. In all of these cases apps will be used less. Will be downloaded less. But for most use cases, that apps have been used for and for many that might not have been conceived of yet, apps are still strong and the best way to achieve your goal. Apps are going to strive. And voice assistants and chatbots are going to strive as well.</p>
<p>But, of course, there are apps that most likely will be used less. And as with all those other media being somewhat replaced by something that fulfills the needs of people better, that's a good thing. Not for the companies doing those apps, not for the devs, designers and product people having to look for something else (though that shouldn't be a problem <em>right now</em>). But for us users. </p>
<p>It's the same thing as usual: Do not fear the future. Be open to it. Embrace it and adapt to it.</p>
<p>Oh, before I forget it: The sames goes for websites. They won't be replaced either. Neither by apps nor by voice assistants or chatbots.</p>
<p>So in short. Those headlines? I would call B.S. But <a href="https://twitter.com/CNN/status/964949743683108865">let's keep that for sh***y politicians</a>.</p>
<p>Note: I am an Google Developer Expert for Android as well as for the Google Assistant. So I have a vested interest in both technologies. But I have much more experience with Android and earn my living mostly with Android. As such I am not unbiased myself <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/">Those &#8220;mobile apps are doomed&#8221; headlines? They are wrong!</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/mobile-apps-doomed-headlines-are-wrong/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using the Actions SDK to Develop for the Google Assistant</title>
		<link>https://www.grokkingandroid.com/using-the-actions-sdk/</link>
					<comments>https://www.grokkingandroid.com/using-the-actions-sdk/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 12 Oct 2017 06:05:56 +0000</pubDate>
				<category><![CDATA[Google Assistant]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Actions SDK]]></category>
		<category><![CDATA[gactions]]></category>
		<category><![CDATA[Google Home]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3719</guid>

					<description><![CDATA[<p>In today's post I'm going to show how to develop a simple app for the Google Assistant. For developing this app, I will be using the Actions SDK. My next post will use Dialogflow (formerly api.ai) instead. After reading both posts you hopefully will know enough to decide which approach is better suited for you. [...]&#160;&#160;<a href="https://www.grokkingandroid.com/using-the-actions-sdk/">Continue Reading&#160;&#160;"Using the Actions SDK to Develop for the Google Assistant"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/using-the-actions-sdk/">Using the Actions SDK to Develop for the Google Assistant</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In today's post I'm going to show how to develop a simple app for the Google Assistant. For developing this app, I will be using the Actions SDK. My next post will use Dialogflow (formerly api.ai) instead. After reading both posts you hopefully will know enough to decide which approach is better suited for you.</p>
<h3>About the app</h3>
<p>In my home town I usually take the bus when taking our youngest to kindergarten before heading off to work. In winter and also due to some long-lasting street works, one of the two lines near our home is quite late all the time. But naturally unreliably so. So I wonder every morning when to leave for the bus. We <em>do</em> have an app for bus information in Münster - but some limitations of this app make it not really suitable for the task.</p>
<p>Thus an assistant app that tells me when the next busses are due and whether we should hurry up or whether we can idle around a bit more is what I'm going to build. The first version in this post with the Actions SDK. Then in the next post an improved version with Dialogflow.</p>
<p>Here's a sketch of what a conversation with this app should look like:</p>
<figure id="attachment_3891" aria-describedby="caption-attachment-3891" style="width: 675px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/sample_dialog_actions_on_google.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/sample_dialog_actions_on_google.png" alt="Sample dialog of the app" width="675" height="819" class="size-full wp-image-3891" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/sample_dialog_actions_on_google.png 675w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/sample_dialog_actions_on_google-412x500.png 412w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/sample_dialog_actions_on_google-577x700.png 577w" sizes="auto, (max-width: 675px) 100vw, 675px" /></a><figcaption id="caption-attachment-3891" class="wp-caption-text">Sample dialog of the app - Made with botsociety.io</figcaption></figure>
<p>On the right is what I'm going to speak. On the left are the assistant's answers. The first is by the assistant itself - I changed the color for that one to emphasize the difference. The second and third are responses of the app. After the last response the app finishes - and with this also the current assistant's action. Thanks to botsociety.io, you can even see this <a href="https://beta.botsociety.io/s/59d101f949b8fc10006481b4">website showcasing this prototype</a>.</p>
<h3>What is the Actions SDK</h3>
<p>The Actions SDK is one way to develop apps for the Google Assistant. As the name of the SDK implies you can create actions which basically are speech snippets of your user and your response to them. Let's go a bit more into the base concepts here.</p>
<p>The relevant things you need to know are:</p>
<ul>
<li>Actions</li>
<li>Intents</li>
<li>Fulfillment</li>
</ul>
<h4>Actions</h4>
<p>An <strong><code class="preserve-code-formatting">action</code></strong> is a wrapper combining an intent and the fulfillment for this intent. For a truly conversational app, where there's a dialog between the user and the assistant, apps have multiple actions. But often it makes sense to create a one-shot app. In this case the app has only one action and answers directly with the response the user is looking for. The sample app would work well as a one-shot app. I only added one more action to make it a better sample for this post.</p>
<h4>Intents</h4>
<p>We already know <strong><code class="preserve-code-formatting">intents</code></strong> from Android. And with Actions on Google they are not much different. An intent specifies what the user <em>intends</em> your app to do.</p>
<p>In contrast to Android, though, you are very limited when it comes to intents with the Actions SDK.</p>
<p>Every app has to define one <strong>actions.intent.MAIN</strong> intent, that is used to start up your app, if no custom intent is better suited to the <a href="https://developers.google.com/actions/discovery/">invocation phrase</a>. Depending on your kind of app, this intent might directly provide the answer and then stop the app. Or it might kind of introduce the app to the user in some way.</p>
<p>For the start of your app you can also define custom intents and which user utterances trigger that intent. You might even add some parameters to that (for example numbers or a date). And if the Assistant detects that one of those phrases was used by the user, it starts up your app using this intent.</p>
<p>If you were to build a more complex app with the Actions SDK, you would use one intent most of the time: <code class="preserve-code-formatting">actions.intent.TEXT</code>. Meaning: You have one intent that has to deal with nearly all possible user input. And thus your app would have to decide what to do based on the text spoken or typed in by the user.</p>
<p>There are <a href="https://developers.google.com/actions/reference/rest/intents">a few more intents</a> available. For example <code class="preserve-code-formatting">android.intent.OPTION</code> which is useful if you provide a set of options to the user of which she might select one. But when dealing with user input most of the time you would have to deal with <code class="preserve-code-formatting">actions.intent.TEXT</code>.</p>
<p>This limitation is the reason why I've written in my <a href="https://www.grokkingandroid.com/actions-on-google-quick-intro/">intro post about the Assistant</a>, that the Action SDK is mostly useful when you are proficient with natural language processing or have a simple project with a command like interface.</p>
<p>Unless you have some language processing super powers it boils down to this:</p>
<p><strong>&#x21E8; Use the Actions SDK for one-shot apps.</strong> These are apps that provide the required answer directly after being invoked and then stop. They give you just this one result. A typical example would be setting a timer to ten minutes.</p>
<p><strong>&#x21E8; For all other apps</strong>, for those that are really conversational, where there are multiple paths to follow and where you want your user to provide more information during the conversation, <strong>I recommend to use Dialogflow (api.ai) instead of the Actions SDK.</strong> I will cover <a href="https://dialogflow.com/">Dialogflow</a> in my next post.</p>
<h4>Fulfillments</h4>
<p><strong><code class="preserve-code-formatting">Fulfillment</code></strong> is just another word for your backend. Every action must be backed by some backend of yours. This is where you generate the text spoken to the user. Or &mdash; on devices that have a graphical user interface &mdash; that's where you create visual cues for your user.</p>
<p>Of course the response is based on which intent was triggered and what additional cues the user gave in her question.</p>
<p>When Google calls your backend, it provides a Json file that contains plenty of information as you will see later in this post. Some of the things you get access to:</p>
<ul>
<li>The spoken text as Google has detected it</li>
<li>The intent invoked</li>
<li>The parameters to the intent</li>
<li>The session id</li>
<li>Information about the device's capabilities</li>
</ul>
<p>In this post I'm only going to make use of some of them, but I'm going to cover more aspects in future posts.</p>
<p>The next picture shows where your app &mdash; or more precisely: your fulfillment code &mdash; fits into the overall picture. The assistant knows which app to call based on the invocation phrase used by the user. It also provides voice recognition of the user utterances and text to speech transformation of your answers to the user. Your app then takes the recognized text and creates an appropriate response for that. </p>
<figure id="attachment_3964" aria-describedby="caption-attachment-3964" style="width: 700px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow-700x410.png" alt="Action SDK workflow" width="700" height="410" class="size-large wp-image-3964" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow-700x410.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow-500x293.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow-768x450.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/action_sdk_workflow.png 1324w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a><figcaption id="caption-attachment-3964" class="wp-caption-text">Action SDK workflow - picture &copy; Google, Inc.</figcaption></figure>
<h3>Preparations</h3>
<p>When you want to use Actions on Google your account must be prepared for that. You have to do three things:</p>
<ol>
<li>Create a project within the Actions on Google Dev Console</li>
<li>Install the <code class="preserve-code-formatting">gactions</code> command line tool</li>
<li>Initialize the project using the <code class="preserve-code-formatting">gactions</code> tool</li>
</ol>
<p>In the next paragraphs I'm going to cover those steps.</p>
<h4>Create a project within the Action on Google Dev Console</h4>
<p>The very first step is to use the <a href="https://console.actions.google.com">Dev Console</a> to create a project. If it's your first project check the terms of the services - since by clicking the "Create Project" button you signify to adhere to them:</p>
<figure id="attachment_3725" aria-describedby="caption-attachment-3725" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project-500x270.png" alt="Creating a project on the dev console" width="500" height="270" class="size-medium wp-image-3725" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project-500x270.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project-768x414.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project-700x378.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/create_actions_project.png 851w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3725" class="wp-caption-text">Creating a project on the Actions on Google Dev Console</figcaption></figure>
<p>Afterwards you have to decide which API to use to build your project:</p>
<figure id="attachment_3978" aria-describedby="caption-attachment-3978" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1-500x347.png" alt="Actions on Google Api / SDK Selection" width="500" height="347" class="size-medium wp-image-3978" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1-500x347.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1-768x533.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1-700x486.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/actions_on_google_project_setup-1.png 1167w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3978" class="wp-caption-text">Actions on Google Api / SDK Selection</figcaption></figure>
<p>As you can see, there are three prominent ways to develop apps: The Actions SDK or one of the two services Dialogflow or Converse AI. If you click on "Actions SDK" you will see a tiny popup where you can copy a <code class="preserve-code-formatting">gactions</code> command. So the next step is to install the <code class="preserve-code-formatting">gactions</code> command line tool.</p>
<h4>Install the gactions command line tool</h4>
<p>You can <a href="https://developers.google.com/actions/tools/gactions-cli">download the gactions tool from Google's site</a>. It's a binary file you can store, wherever you see fit. Make sure to make this file executable (if you're using Linux or Mac OS X) and - since you're going to use this tool a lot - I recommend to add it to your PATH.</p>
<p>If you already had this tool installed, you can use the <code class="preserve-code-formatting">selfupdate</code> option to update it:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
gactions selfupdate</code></pre>
</div>
<p>That's all that is needed in this step 🙂</p>
<h4>Initialize the project using the gactions tool</h4>
<p>The last step is to simply initialize your project. Afterwards you're set to start developing actions using the Actions SDK.</p>
<p>Simply create some folder in which you whish to create the project and then switch to this folder.</p>
<p>Within this folder enter</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">gactions init</code></pre>
</div>
<p>If you have never run <code class="preserve-code-formatting">gactions</code> before, it will require authorization to access the Actions Console. Simply follow the steps outlined on the command line. After pasting your authorization code into the command line, Google gets your access token which is used for all subsequent communication between the <code class="preserve-code-formatting">gactions</code> tool and the Actions Console. If you ever want to use another account, simply remove the <code class="preserve-code-formatting">creds.data</code> file.</p>
<p>The <code class="preserve-code-formatting">gactions init</code> command will create a file named <code class="preserve-code-formatting">action.json</code>. This file contains the configuration of your project. In it's current state it's content is not valid. It contains plenty of <code class="preserve-code-formatting">&lt;INSERT YOUR ... HERE&gt;</code> markers. You are going to fill those in in the remainder of this post.</p>
<p>With this you have finished the preparations and are good to go. So let's start creating an action.</p>
<h3>The config file explained</h3>
<p>Let's start by looking at the <code class="preserve-code-formatting">actions.json</code> file that was just created for us:</p>
<div class="sourcecode">
<pre class="language-json line-numbers"><code class="language-json line-numbers">
{
    "actions": [
      {
        "description": "Default Welcome Intent",
        "name": "MAIN",
        "fulfillment": {
          "conversationName": "&lt;INSERT YOUR CONVERSATION NAME HERE&gt;"
        },
        "intent": {
          "name": "actions.intent.MAIN",
          "trigger": {
            "queryPatterns": [
              "talk to &lt;INSERT YOUR NAME HERE&gt;"
            ]
          }
        }
      }
    ],
    "conversations": {
      "&lt;INSERT YOUR CONVERSATION NAME HERE&gt;": {
        "name": "&lt;INSERT YOUR CONVERSATION NAME HERE&gt;",
        "url": "&lt;INSERT YOUR FULLFILLMENT URL HERE&gt;"
      }
    }
}</code></pre>
</div>
<p>As you can see, some objects match the concepts explained above. At the top you have the <code class="preserve-code-formatting">actions</code> object, which contains an array of <code class="preserve-code-formatting">action</code> objects - each of which contains one <code class="preserve-code-formatting">intent</code>. The second object is named <code class="preserve-code-formatting">conversations</code>, which contains a map of <code class="preserve-code-formatting">conversation</code> objects. I don't know why it's named "conversations", but basically this object covers the description of where to find the app's fulfillment.</p>
<p>You can <a href="https://developers.google.com/actions/reference/rest/Shared.Types/ActionPackage">see the full specs in the reference section</a> for Actions on Google.</p>
<h4>The config file of the sample app</h4>
<p>The sample app has one intent to deal with the start of the app - the <code class="preserve-code-formatting">actions.intent.MAIN</code> intent. </p>
<p>This app is a good example for a one-shot app - meaning it would provide the answer directly with the <code class="preserve-code-formatting">actions.intent.MAIN</code> intent and finish itself directly after giving the answer. </p>
<p>To make this tutorial more useful, I've added the possibility for the user to acknowledge the answer of the app before it ends itself and gives the control back to the assistant. And - if the user didn't understand the answer - she can ask for a repetition.</p>
<p>Thus there is one intent of type <code class="preserve-code-formatting">actions.intent.TEXT</code> that deals with both of these follow-up responses by the user and that also provides an answer in case the app doesn't understand the user's intention.</p>
<p>The resulting actions part looks now like this:</p>
<div class="sourcecode">
<pre class="language-json line-numbers"><code class="language-json line-numbers">
{
  "actions": [
    {
      "description": "Default Welcome Intent",
      "name": "MAIN",
      "fulfillment": {
        "conversationName": "do-i-have-to-rush"
      },
      "intent": {
        "name": "actions.intent.MAIN",
        "trigger": {
          "queryPatterns": [
            "talk to let's rush",
            "let's rush",
            "do i have to rush",
            "do i have to hurry",
            "start let's rush"
          ]
        }
      }
    },
    {
      "description": "Everything Else Intent",
      "name": "allElse",
      "fulfillment": {
        "conversationName": "do-i-have-to-rush"
      },
      "intent": {
        "name": "actions.intent.TEXT"
      }
    }
  ],
  "conversations": {
    "do-i-have-to-rush": {
      "name": "do-i-have-to-rush",
      "url": "&lt;INSERT YOUR FULLFILLMENT URL HERE&gt;"
  	}
  }
}</code></pre>
</div>
<p>The <strong><code class="preserve-code-formatting">intent</code></strong> represents the type of information the user tells the app. You first have to specify a <code class="preserve-code-formatting">name</code> for this intent and then you have to define how this intent can be triggered by the user. So basically what the user has to say, in order for the assistant to select this intent.</p>
<p>As you can see from the Json above, the <code class="preserve-code-formatting">trigger</code> contains an array of possible phrases. You can use it for custom intents - but also for the initial, the main intent. My sample app has the name "Do I have to Rush".<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_3719_10('footnote_plugin_reference_3719_10_1');" onkeypress="footnote_moveToReference_3719_10('footnote_plugin_reference_3719_10_1');" ><sup id="footnote_plugin_tooltip_3719_10_1" class="footnote_plugin_tooltip_text">1)</sup></a><span id="footnote_plugin_tooltip_text_3719_10_1" class="footnote_tooltip"></span></span> But the user might use other phrases to trigger your app. In the prototype shown at the beginning of this post, I am using "Let's rush". And that is working as well because I added that phrase to the trigger section of the intent.</p>
<p>For <code class="preserve-code-formatting">actions.intent.TEXT</code>  intents you do not need to specify trigger phrases - since this intent gets called automatically for follow-up phrases of the user.</p>
<p>The above file is still incomplete. While the fulfillments link to a conversation, the conversation's URL is still not set. I will add that information after I've created the function in the next section. I am using <a href="http://www.grokkingandroid.com/primer-cloud-functions-for-firebase">Cloud Functions for Firebase</a> - and the URL can only be set after deploying for the first time. </p>
<p>About time to delve into the fulfillment code.</p>
<h3>The fulfillment code</h3>
<p>In the config file you specified how many and which intents you have. In your fulfillment you have to provide the responses to these intents. That is: You tell the assistant what to say to the user and - if the device is capable of those - what visual elements to show the user.</p>
<p>For the fulfillment's backend I am going to use Firebase's Cloud Functions with Javascript. Please see my <a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/">introduction tp Cloud Functions for Firebase</a> and especially the section on <a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase#setup">setting up your Cloud Functions project</a> to create the necessary files and project structure.</p>
<p>If you want to follow along <a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase#setup">set up your project</a> as described in my previous post.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_3719_10('footnote_plugin_reference_3719_10_2');" onkeypress="footnote_moveToReference_3719_10('footnote_plugin_reference_3719_10_2');" ><sup id="footnote_plugin_tooltip_3719_10_2" class="footnote_plugin_tooltip_text">2)</sup></a><span id="footnote_plugin_tooltip_text_3719_10_2" class="footnote_tooltip"></span></span></p>
<h4>The Actions On Google Client Library</h4>
<p>Google provides us with an <a href="https://github.com/actions-on-google/actions-on-google-nodejs">Actions on Google client library for Javascript</a>. For the code in this tutorial I'm making use of that lib.</p>
<p class="textbox">
Note that there is also an <a href="https://github.com/TicketmasterMobileStudio/actions-on-google-kotlin">unofficial Kotlin port</a> available. I haven't had a look at it, since I prefer to use Cloud Functions. Anyway: If anyone has experience with it, please let me know in the comments or on social media.
</p>
<p>Assuming you have created the necessary structure with <code class="preserve-code-formatting">firebase init</code> the next step is to add Google's library to your project.</p>
<p>The simplest way to do so, is to use <code class="preserve-code-formatting">npm install</code> within the functions folder of your project:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
npm install actions-on-google</code></pre>
</div>
<p>You will get a result telling you the number of installed packages. And your <code class="preserve-code-formatting">package.json</code> file afterwards contains this additional dependency:</p>
<div class="sourcecode">
<pre class="language-json line-numbers"><code class="language-json line-numbers">
{
//...
  "dependencies": {
    "actions-on-google": "^1.5.0",
    //...
  },
//...
}</code></pre>
</div>
<p>1.5.0 is the most recent version while writing this post. But when you read this, the newest version might very well have a higher version number since Google is eagerly working on everything related to the Google Assistant.</p>
<p>If you want to update to a newer version, you can update the version using </p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
npm update actions-on-google</code></pre>
</div>
<h3>The fulfillment function</h3>
<p>When it comes to the actual function code, you have to do three things:</p>
<ol>
<li>Initialize the Assistant library</li>
<li>Create a mapping from intents to functions</li>
<li>Write a function for every intent</li>
</ol>
<h4>Your function after <code class="preserve-code-formatting">firebase init</code></h4>
<p>You already should have code similar to this in your project if you set up Cloud Functions correctly:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
const functions = require('firebase-functions');

/**
 * This function is exposed via Firebase Cloud Functions.
 * It determines the next busses leaving from the
 * closest busstop to our home.
 *
 * You normally create one function for all intents. If you
 * want to use more functions, you have to configure all
 * those fulfillment endpoints.
 *
 * Note: Your fulfillment must respond within five seconds.
 * For details see the blue box at the top of this page:
 * https://developers.google.com/actions/sdk/deploy-fulfillment
 */
exports.shouldIRush = functions.https.onRequest((request, response) =&gt; {
   // some generated stuff you can safely delete
}</code></pre>
</div>
<h4>Add the Google Actions on Google SDK</h4>
<p>The very first step is to add your the <code class="preserve-code-formatting">actions-on-google</code> dependency at the top and to create the <code class="preserve-code-formatting">ActionsSdkApp</code> object within the function:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
const functions = require('firebase-functions');
var ActionsSdkApp = require('actions-on-google').ActionsSdkApp;

/**
 * ...
 */
exports.shouldIRush = functions.https.onRequest((request, response) =&gt; {
    let app = new ActionsSdkApp({request, response});
    // ...
}</code></pre>
</div>
<p>Note that you are using a specific part of the <code class="preserve-code-formatting">actions-on-google</code> lib. You only need the <code class="preserve-code-formatting">ActionsSdkApp</code>. In my next post about Dialogflow this will change and you will use the <code class="preserve-code-formatting">DialogflowApp</code> instead. You must not forget the specific part you are interested in nor must you use the wrong one. One thing you need to know: In its samples, Google usually uses an <code class="preserve-code-formatting">ActionsSdk</code> alias for the <code class="preserve-code-formatting">ActionsSdkApp</code> class.</p>
<p>When you have added the lib and create the object, you can use the app object to query for information about the request and to provide the answer to the user. </p>
<h4>Create the mapping from intents to your handler functions</h4>
<p>As you've seen in the <code class="preserve-code-formatting">action.json</code> file, the sample project has a <code class="preserve-code-formatting">main</code> and an <code class="preserve-code-formatting">allElse</code> action. So first, let's create empty functions for those two action's intents. Next we create a mapping from the two intents to these two functions. Note that the mapping is based on the intent name and not the action name. Finally call <code class="preserve-code-formatting">app.handleRequest()</code> with this mapping to allow the lib to do it's magic:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
exports.shouldIRush = functions.https.onRequest((request, response) =&gt; {
  let app = new ActionsSdkApp({request, response});
  //..
  function handleMainIntent() {
  }
  
  function handleTextIntent() {
  }
  
  // finally: create map and handle request
  // map all intents to specific functions
  let actionMap = new Map();
  actionMap.set(app.StandardIntents.MAIN, handleMainIntent);
  // all follow-up requests will trigger the next intent.
  // Be sure to include it.
  actionMap.set(app.StandardIntents.TEXT, handleTextIntent);
  
  // apply this map and let the sdk parse and handle the request
  // and your responses
  app.handleRequest(actionMap);
}</code></pre>
</div>
<h4>Write a function for every intent</h4>
<p>Now I'm not going to show all I've done within those functions. I simply highlight some specific aspects, that are important to understand the Actions SDK.</p>
<p>For my intents I simply call the usecase:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
function handleMainIntent() {
    console.log(`starting mainIntent - ${getDebugInfo()} - at: ${new Date()}`);
    usecase.callApiAndPrepareResponse(new UsecaseCallback());
}

function handleTextIntent() {
    console.log(`starting textIntent - ${getDebugInfo()} - at: ${new Date()}`);
    usecase.handleFollowUpPhrases(app.getRawInput(), new UsecaseCallback());
}</code></pre>
</div>
<p>The usecase generates the response that the assistant should present to the user. With those texts it then calls the appropriate methods of the callback object. The callback object passed to the usecase is of this type:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
class UsecaseCallback {
    answerNormalRequestSuccessfully(answerText) {
        app.ask(answerText);
    }
    answerNormalRequestWithErrorMessage(errorMessage) {
        app.ask(errorMessage);
    }
    endConversation() {
        app.tell('See you!');
    }
    reactToUnknownPhrase() {
        // If nothing matches, you might consider providing some help
        // to the user; I omit this for this simple usecase.
        app.ask('I\'m sorry, but I\'m not able to help you with this.');
    }
}</code></pre>
</div>
<p>So sometimes I call <code class="preserve-code-formatting">app.ask()</code> with a text and in one case I call <code class="preserve-code-formatting">app.tell()</code>. Even though the former is named "ask" it doesn't necessarily mean it has to be a question. In my case the answer is presented using <code class="preserve-code-formatting">ask()</code>. But <code class="preserve-code-formatting">ask()</code> keeps the conversation alive. It basically expect another user reaction. The <code class="preserve-code-formatting">tell()</code> method on the other hand doesn't expect a user reaction. In fact it closes the conversation and passes the baton back to the Assistant itself.</p>
<p>Of course there are more options available than just to ask or to tell, but I won't go into them.</p>
<p>From the code above you can see, that I also have a function to generate some debugging information:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
function getDebugInfo() {
    // you can get some userId - but for getting the name, you would
    // need the appropriate permission.
    // be very careful what you use in production here;
    // logging too much can cause privacy issues
    return `user: ${app.getUser().userId} - conversation: ${app.getConversationId()}`;
}</code></pre>
</div>
<p>While the usefulness of the <code class="preserve-code-formatting">userId</code> depends on a few factors, the <code class="preserve-code-formatting">conversationId</code> is nearly always useful. For one, you can use it to store conversation state on your backend. Since you only have limited possibilities to keep a conversational state with Actions on Google this id can be used as a key for that.</p>
<p>A second good use for the <code class="preserve-code-formatting">conversationId</code> is for tracking down problems by using this id within all of your log messages and thus enabling you to join all log messages of one conversation together.</p>
<table>
<caption>A few important methods and objects of the ActionSdkApp object</caption>
<tr>
<th>Method / Attribute</th>
<th>Type</th>
<th>Use</th>
</tr>
<tr>
<td>ask</td>
<td>method</td>
<td>Presents text to the user and awaits a textual answer</td>
</tr>
<tr>
<td>tell</td>
<td>method</td>
<td>Presents text to the user and ends the conversation</td>
</tr>
<tr>
<td>getAvailableSurfaces</td>
<td>method</td>
<td>Returns a set of Surface objects. Those currently can be SurfaceCapabilites.AUDIO_OUTPUT or SurfaceCapabilites.SCREEN_OUTPUT</td>
</tr>
<tr>
<td>askForPermission</td>
<td>method</td>
<td>Requests the specified permissions from the user</td>
</tr>
<tr>
<td>getDeviceLocation</td>
<td>method</td>
<td>The location of the device or <code class="preserve-code-formatting">null</code> if no permission has been requested/granted</td>
<tr>
<td>buildCard</td>
<td>method</td>
<td>One of the many methods to present a visual output if the devices supports that</td>
</tr>
<tr>
<td>StandardIntents</td>
<td>object</td>
<td>Contains all available standard intents as constants (e.g. StandardIntents.TEXT)</td>
</tr>
<tr>
<td>SupportedPermissions</td>
<td>object</td>
<td>Contains all available permissions as constants (e.g. SupportedPermissions.NAME)</td>
</tr>
</tr>
</table>
<h3>Deploy the fulfillment function to Firebase</h3>
<p>To deploy your fulfillment function, simply call </p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase deploy</code></pre>
</div>
<p>Th deployment lasts a few seconds and when it's done, you get the function URL, you can use in the <code class="preserve-code-formatting">conversations</code> section of the <code class="preserve-code-formatting">action.json</code> file. Simply copy this url and replace the <code class="preserve-code-formatting">&lt;INSERT YOUR FULFILLMENT URL HERE&gt;</code> placeholder with your url:</p>
<div class="sourcecode">
<pre class="language-json line-numbers"><code class="language-json line-numbers">
{
//...
  "conversations": {
    "do-i-have-to-rush": {
      "name": "do-i-have-to-rush",
      "url": "https://us-central1-gcloinudProjectId.cloudfunctions.net/yourFunction"
    }
  }
//...
}</code></pre>
</div>
<h3>Deploying an app to the Actions Console</h3>
<p>If you have deployed your code to Firebase and configured your <code class="preserve-code-formatting">action.json</code> file, all you have to do, is to deploy your app to the Actions Console.</p>
<p>Actually all Google needs, is your <code class="preserve-code-formatting">actions.json</code> file - or files in case of <a href="https://developers.google.com/actions/localization/action-packages">internationalized</a> apps. It's not as if you deploy code to the Actions Console. You only <em>define</em> your actions and where to find your code.</p>
<p>So to upload the newest version of your file simply issue this command:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
gactions update --action_package action.json --project yourActionsConsoleId</code></pre>
</div>
<p>Now if you do not know the Action Console id anymore, simply go the the Actions Console, select the project and click on the gear icon. Then select "Project settings" to see the project id:</p>
<figure id="attachment_3983" aria-describedby="caption-attachment-3983" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/project_settings.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/project_settings-500x175.png" alt="Find out the id via project settings" width="500" height="175" class="size-medium wp-image-3983" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/project_settings-500x175.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/project_settings.png 577w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3983" class="wp-caption-text">Select the project settings to find out the id of your project</figcaption></figure>
<h3>Testing the Actions SDK based app</h3>
<p>Google provides a web-based testing tool for actions which is really a good way to test and demonstrate your app:</p>
<figure id="attachment_3771" aria-describedby="caption-attachment-3771" style="width: 700px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1-700x528.png" alt="Running your app in the emulator" width="700" height="528" class="size-large wp-image-3771" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1-700x528.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1-500x377.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1-768x580.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/actions_simulator-1.png 1407w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a><figcaption id="caption-attachment-3771" class="wp-caption-text">Running an assistant app in the web based emulator</figcaption></figure>
<p>You can test your app also on your Google Home, your Android or iOS devices and on any other device that offers the assistant (for example the <a href="https://aiyprojects.withgoogle.com/">AIY based devices</a>). To do so, those devices must use the same account and must match the locale of your test.</p>
<p>But before you can test, you must enable the test. The easiest way is to use the command line:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
gactions test --action_package action.json --project yourActionsConsoleId</code></pre>
</div>
<p>But you can also enable testing in the Actions Console. Simply go to your project and click on the "Simulator" link in the menu on the left and than click the "Start Testing" button.</p>
<figure id="attachment_3985" aria-describedby="caption-attachment-3985" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project.png"><img loading="lazy" decoding="async" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project-500x379.png" alt="Enable testing via the Actions Console" width="500" height="379" class="size-medium wp-image-3985" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project-500x379.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project-768x582.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project-700x531.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/10/start_testing_actions_console_project.png 790w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3985" class="wp-caption-text">Enable testing via the Actions Console</figcaption></figure>
<p>While writing this, I do not see this button for <em>one</em> project  or get an error when trying to enable testing via command line due to a <a href="https://stackoverflow.com/q/46650524/1419069">glitch on Google's side</a>. As I've mentioned, Google is working a lot on Actions on Google. The downside of this is, that there are occassional hiccups. One this week, <a href="https://twitter.com/RittmeyerW/status/915964111883837442">one last week</a>. In both cases, though, the response by the Google team (alerted via the <a href="https://plus.google.com/communities/105684267327487893574">Actions on Google community on Google+</a>) was quick and helpful.</p>
<h3 id="actions-sdk-sample">Sample project</h3>
<p>For more detailed code see my <a href="https://github.com/writtmeyer/actionssdk-sample">ActionsSDK sample project</a> on github. On <a href="https://github.com/writtmeyer/actionssdk-sample">github</a> you find the full implementation of the sample app outlined at the beginning of this post.</p>
<p>After cloning the sample project, you have to install all the packages. Switch into the <code class="preserve-code-formatting">functions</code> folder of the project and issue the following command:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
npm install</code></pre>
</div>
<p>The project only contains the cloud function's code and the <code class="preserve-code-formatting">action.json</code> file. So be sure to follow the relevant steps of this tutorial for deploying the function and deploying the project to the Actions Console.</p>
<h3>Summary</h3>
<p>Creating this project was fun. But it also made obvious the current limitations with the Actions SDK approach. To judge for yourself have a look at the <code class="preserve-code-formatting">timetable-usecase.js</code> file. That's not the best and most flexible way to react to user phrases 🙂</p>
<p>Thus for anything other than one-shot apps I recommend to use Dialogflow. In one of my next posts, I'm going to improve upon this app by switching to Dialogflow.</p>
<p>Until next time!</p>
<p class="increased-margin">Ok, <strike>Google</strike> dear reader, what's your take on this? What are you going to do with the Actions SDK? Please let me know.</p>
<div class="speaker-mute footnotes_reference_container"> <div class="footnote_container_prepare"><p><span role="button" tabindex="0" class="footnote_reference_container_label pointer" onclick="footnote_expand_collapse_reference_container_3719_10();">Footnotes</span><span role="button" tabindex="0" class="footnote_reference_container_collapse_button" style="display: none;" onclick="footnote_expand_collapse_reference_container_3719_10();">[<a id="footnote_reference_container_collapse_button_3719_10">+</a>]</span></p></div> <div id="footnote_references_container_3719_10" style=""><table class="footnotes_table footnote-reference-container"><caption class="accessibility">Footnotes</caption> <tbody> 

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_3719_10('footnote_plugin_tooltip_3719_10_1');"><a id="footnote_plugin_reference_3719_10_1" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>1</a></th> <td class="footnote_plugin_text">According to the <a href="https://developers.google.com/actions/discovery/">invocation recommendations by Google</a>, "Do I have to rush" is not a good name. You should try to find more concise and still expressive names for your projects.</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_3719_10('footnote_plugin_tooltip_3719_10_2');"><a id="footnote_plugin_reference_3719_10_2" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>2</a></th> <td class="footnote_plugin_text">In my <a href="https://github.com/writtmeyer/actionssdk-sample">sample app on github</a> I am using outbound http traffic. As you can see on the <a href="https://firebase.google.com/pricing/">pricing information for Firebase</a>, you cannot do so with the cost-free Spark plan. So I've configured my project to used the Blaze plan, the pay as you go plan. Even with this plan you have a significantly sized free tier - meaning free invocations, free CPU usage and free outbound traffic that should be more than sufficient for getting used with the Actions SDK and using Cloud Functions for Firebase for testing purposes. But still: You must have billing enabled and you might run into costs.</td></tr>

 </tbody> </table> </div></div><script type="text/javascript"> function footnote_expand_reference_container_3719_10() { jQuery('#footnote_references_container_3719_10').show(); jQuery('#footnote_reference_container_collapse_button_3719_10').text('−'); } function footnote_collapse_reference_container_3719_10() { jQuery('#footnote_references_container_3719_10').hide(); jQuery('#footnote_reference_container_collapse_button_3719_10').text('+'); } function footnote_expand_collapse_reference_container_3719_10() { if (jQuery('#footnote_references_container_3719_10').is(':hidden')) { footnote_expand_reference_container_3719_10(); } else { footnote_collapse_reference_container_3719_10(); } } function footnote_moveToReference_3719_10(p_str_TargetID) { footnote_expand_reference_container_3719_10(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } } function footnote_moveToAnchor_3719_10(p_str_TargetID) { footnote_expand_reference_container_3719_10(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } }</script><p>The post <a href="https://www.grokkingandroid.com/using-the-actions-sdk/">Using the Actions SDK to Develop for the Google Assistant</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/using-the-actions-sdk/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>A Primer on Cloud Functions for Firebase</title>
		<link>https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/</link>
					<comments>https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 22 Aug 2017 09:35:22 +0000</pubDate>
				<category><![CDATA[Cloud]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Cloud Functions]]></category>
		<category><![CDATA[Firebase]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3757</guid>

					<description><![CDATA[<p>Since I am going to use Cloud Functions For Firebase a bit more in coming posts on this blog, I am going to give a very brief overview of how you can use and test them. What are Cloud Functions for Firebase Cloud Functions is a node.js based offering where you can expose stateless services. [...]&#160;&#160;<a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/">Continue Reading&#160;&#160;"A Primer on Cloud Functions for Firebase"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/">A Primer on Cloud Functions for Firebase</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Since I am going to use <a href="https://cloud.google.com/functions/">Cloud Functions For Firebase</a> a bit more in coming posts on this blog, I am going to give a very brief overview of how you can use and test them.</p>
<h3>What are Cloud Functions for Firebase</h3>
<p>Cloud Functions is a <a href="https://nodejs.org/en/">node.js</a> based offering where you can expose stateless services. You can use it to react to certain Firebase events (not covered in this post) or to react to http events. They are more or less the same as <a href="https://cloud.google.com/functions/">Google Cloud Functions</a> but are triggered by other events. Of course you have access to all those other Firebase services from within Cloud Functions for Firebase.</p>
<p>Warning: I am only describing functions <a href="https://firebase.google.com/docs/functions/http-events">triggered by http</a>. I do not deal with the realtime database or the storage triggers and so on. If you're interested in the full list of possible triggers, see the <a href="https://firebase.google.com/docs/functions/#key_capabilities">official documentation</a>.</p>
<h3 id="setup">Setting Cloud Functions up</h3>
<p>First of all: You need <a href="https://www.npmjs.com/">npm</a> installed. npm is a package manager for Javascript modules and (command line) tools. It's part of the <a href="https://nodejs.org/en/">node.js</a> ecosystem - and thus you install it by installing node.js. I assume you have node.js and npm installed. Otherwise go to the node.js website and click on the big download links to install it (or use the respective Linux or OS X tools for installing packages). Make sure, you use the LTS version - the newest version is not supported by Firebase.</p>
<h4>Install the Firebase command line tools</h4>
<p>After you have npm installed, you need to install the Firebase tools. If you're using Firebase Hosting, you should have those tools already installed. If not, simply install them using npm:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
npm install -g firebase-tools</code></pre>
</div>
<p>You can use the same command to update the Firebase command line tools later on. Since Google updates them frequently, Google recommends to use the latest version. So even if you already have them installed, you might want to update.</p>
<p>To check which version you're using, use </p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase --version</code></pre>
</div>
<h4>Authorize the firebase command line tools</h4>
<p>The next step is to authorize the command line tools to use your credentials. Start this process by using</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase login</code></pre>
</div>
<p>The tool asks whether you want to provide anonymous stats and afterwards starts the browser (should this not work automatically, it prints a rather longish URL to copy into your browser). As usual you get a list of things the command line tools need to do and you can grant the necessary permission to do so, by clicking "Allow".</p>
<h4>Initializing project</h4>
<p>If you want to create a new project in the <a href="https://console.firebase.google.com/">web-based Firebase Console</a>, now would be the right time to do so. Afterwards switch back to the command line.</p>
<p>Unless you haven't done so already, you should switch to the folder in which you want to create your Cloud Functions for Firebase project. Within this folder create the project by calling</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase init</code></pre>
</div>
<p>You will see something like this:</p>
<figure id="attachment_3795" aria-describedby="caption-attachment-3795" style="width: 700px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1-700x199.png" alt="Inisitializing a Firebase project" width="700" height="199" class="size-large wp-image-3795" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1-700x199.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1-500x142.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1-768x218.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/firebase_init-1.png 1503w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a><figcaption id="caption-attachment-3795" class="wp-caption-text">Inisitializing a Firebase project</figcaption></figure>
<p>You can navigate to the second option using the up/down keys on your keyboard and then select "Functions: Configure and deploy Cloud Functions" by pressing space when the arrow points to this option. With pressing space again, you can deselect selected options.</p>
<p>In the next step you have to select the Firebase project you want your Cloud Functions to be associated with. Again use your arrow keys and space to select the appropriate option. Even though there is a "create a new project" option, I recommend to create the project in the webbased Firebase console before running firebase init. You can abort the tool at any time with Ctrl-D or Ctrl-C.</p>
<p>Afterwards the tool creates the necessary project structure for creating Cloud Functions and deploying them to Firebase.</p>
<p>The Firebase command line tool creates the npm dependencies by default, but before it does so, it asks you, whether it should do so. I recommend installing the dependencies, you will need them anyway. So simply hit enter when the question pops up. </p>
<p>If you are using Sonartype or any other private npm repository, you shouldn't install the dependencies. Instead you have to change the created <code class="preserve-code-formatting">package.json</code> file after the project has been set up, so that it points to your repository url.</p>
<h3 id="structure">Structure of a Cloud Functions project</h3>
<p>After having set up the project the project structure looks like this:</p>
<figure id="attachment_3801" aria-describedby="caption-attachment-3801" style="width: 292px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/project_structure.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/project_structure.png" alt="Project structure" width="292" height="272" class="size-full wp-image-3801" /></a><figcaption id="caption-attachment-3801" class="wp-caption-text">The project structure of a freshly created Cloud Functions for Firebase project</figcaption></figure>
<p>The top level folder contains relevant information for Firebase. The <code class="preserve-code-formatting">.firebaserc</code> file for example contains the information to which Firebase project the function should be deployed. </p>
<p>The <code class="preserve-code-formatting">functions</code> folder contains your Javascript code. The starting point for your project is the file <code class="preserve-code-formatting">index.js</code>, though you might have more Javascript files than just this one. Within the <code class="preserve-code-formatting">functions</code> folder there's also the file <code class="preserve-code-formatting">package.json</code>, that contains information about how to package your project.</p>
<p>Finally there's the sub-folder <code class="preserve-code-formatting">node_modules</code> that contains all the necessary dependencies of your project. Even without anything added by yourself, it contains already quite a lot of modules. </p>
<h3 id="signature">Signature of the called function</h3>
<p>You need to add the <code class="preserve-code-formatting">firebase-functions</code> module to your code and - obviously - the code of your function. </p>
<p>The bare minimum looks like this:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
const functions = require('firebase-functions');

exports.yourFunction = functions.https.onRequest((req, res) =&gt; {
    // your code goes here
});</code></pre>
</div>
<p>With this code, you export the function <code class="preserve-code-formatting">yourFunction</code>. While I will cover deployment a bit down, for now it's enough to know that the firebase command line tool deploys all exported functions by default. You can use as many functions as you like within your <code class="preserve-code-formatting">index.js</code>. Just remember to keep your code concise and tidy and <a href="https://quickleft.com/blog/creating-and-publishing-a-node-js-module/">consider using your own modules</a> to keep the logic separate from your functions.</p>
<p>The <code class="preserve-code-formatting">req</code> and <code class="preserve-code-formatting">res</code> paramters are the same <a href="http://expressjs.com/en/4x/api.html#req">Request</a> and <a href="http://expressjs.com/en/4x/api.html#res">Response</a> objects you might know from <a href="http://expressjs.com/">Express</a> - a very common framework to develop webapps with node.js.</p>
<p>With the <code class="preserve-code-formatting">Request</code> object you can get more information about the request. For example you can get access to the headers and the body of the http request or to the the query string used for the request.</p>
<p>You need the <code class="preserve-code-formatting">Response</code> object to generate the answer you want to send back to the client. You can set the statuscode, set headers and a body in your response.</p>
<p class="textbox">
I strongly recommend to use <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> with Javascript. Otherwise Javascript is simply too forgiving, which will hurt you more often than not. One important thing strict mode takes care of, is to prevent your code from accidentally creating global variables.
</p>
<p>With strict mode enabled and with making use of some features of the respective objects, the typical Hello World sample could look like this:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
"use strict";

const functions = require('firebase-functions');

exports.yourFunction = functions.https.onRequest((req, res) =&gt; {
    let name;
    if (req.query.name) {
        name = req.query.name;
    }
    else {
        name = "World";
    }
    res.contentType("application/json");
    res.send(JSON.stringify({ "result": "Hello " + name }));
    res.status(200);
    res.end();
});</code></pre>
</div>
<h3 id="testing">Unit testing a function</h3>
<p>Unit testing Cloud Functions is not really a problem. You have to call your function and assert that it does what you want it to do. So basically you have to verify, that the <code class="preserve-code-formatting">res</code> object is in the expected state after your function has been executed.</p>
<p>Bofore coding tests, you need to have the necessary test libs. I'm using <a href="http://mochajs.org/">Mocha</a> for running the tests and <a href="http://chaijs.com/">Chai</a> for testing assertions in a nice way using <a href="http://chaijs.com/guide/styles/#should">Chai's should assertion style</a>.</p>
<p>I recommend to install Mocha globally and Chai locally:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
npm install -g mocha
npm install -D chai</code></pre>
</div>
<p>The option <code class="preserve-code-formatting">-D</code> ensures that the lib is not packaged when you deploy your function, while still being available when running your tests.</p>
<p>Mocha expects test code to be within a subfolder named <code class="preserve-code-formatting">test</code>. I consider this to be a good default and thus follow along. To get access to my system under test, I simply have to point to the parent directory, when importing the function:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
const subject = require("../index.js")</code></pre>
</div>
<p>For testing the function you have to create mock objects for the request and response objects you pass into the function. If you use the realtime database, storage or anything else from within your functions, you have to mock these as well. You could use <a href="http://sinonjs.org/">Sinon</a> for that, but Javascript makes mocking very easy. So sometimes that's not even necessary. </p>
<p>For example I create a mock <code class="preserve-code-formatting">status()</code> function on the response object, since I set the status using this method in my code.</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
"use strict";

const chai = require('chai');

describe("Sample Functions", function () {
    const subject = require("../index.js")
    let req;
    let res;
    chai.should();

    beforeEach(function () {
        req = {
            "query": {}
        };
        res = {
            "shadow": {
                "statusCode": 999,
                "noOfEndCalls": 0,
                "contentType": ""
            },
            body: {},
            contentType: function(contentType) {
                this.shadow.contentType = contentType;
            },
            status: function (statuscode) {
                this.shadow.statusCode = statuscode;
            },
            end: function() {
                this.shadow.noOfEndCalls++;
            },
            send: function(bodyText) {
                this.body = JSON.parse(bodyText);
            }
        };
    });

    it('someFunctions should return Hello World in body json', function () {
        subject.yourFunction(req, res);
        verifyCommonResults(res);
        let expected = { "result": "Hello World" };
    });

    it('someFunctions should return Hello Assistant in body json', function () {
        req = {
            "query": {
                "name": "Assistant"
            }
        };
        subject.yourFunction(req, res);
        verifyCommonResults(res);
        let expected = { "result": "Hello Assistant" };
        res.body.should.eql(expected);
    });

    function verifyCommonResults(res) {
        res.shadow.statusCode.should.eql(200);
        res.shadow.noOfEndCalls.should.eql(1);
        res.shadow.contentType.should.eql("application/json");
    }
});</code></pre>
</div>
<p>If you installed mocha globally, you can now run the test using</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
mocha test</code></pre>
</div>
<p>Another option is to define a <code class="preserve-code-formatting">script</code> section at the root level in your <code class="preserve-code-formatting">package.json</code> file and use <code class="preserve-code-formatting">npm test</code> to run your tests instead:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
"scripts": {
  "test": "mocha test"
}</code></pre>
</div>
<h4>Mocking outbound http calls</h3>
<p>An important thing is to <strong>mock outbound traffic</strong> if you connect to an external endpoint.	For this I use <a href="https://github.com/node-nock/nock">Nock</a>. Nock is very powerful and comes with a <a href="https://github.com/node-nock/nock">good documentation about all of nock's options</a>. A very simply example looks like this:</p>
<div class="sourcecode">
<pre class="language-js line-numbers"><code class="language-js line-numbers">
var nock = require('nock');
var api = nock('http://myexternalapi.com')
    .get('/mytestpath/')
    .reply(200, '{"dummy": "Hello World"}');</code></pre>
</div>
<p>The next request to <code class="preserve-code-formatting">http://myexternalapi.com/mytestpath/</code> would then be answered with the Json specified.</p>
<h3>Running a function locally</h3>
<p>Before deploying a function you should test it locally. The command <code class="preserve-code-formatting">firebase serve</code> does just that:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase serve --only function</code></pre>
</div>
<p>If you forget to add the <code class="preserve-code-formatting">--only function</code> part, you will get a rather useless error message:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
"Error: An unexpected error has occurred."</code></pre>
</div>
<p>Alas, starting the local server is not really a very fast option. You have to wait a few seconds until a localhost URL is printed for your function. After that, you can use it - either by loading the URL in your browser, using <a href="https://www.getpostman.com/">Postman</a> or by using <code class="preserve-code-formatting">curl</code>. </p>
<p>There won't be a log file, but any <code class="preserve-code-formatting">console.log()</code> output of your code will be printed directly to the command line. Not perfect, but sufficient for local testing.</p>
<p>Even though the local deployment is too slow for my liking, it really helps detect flaws - especially in the begining, when you're not entirely sure what your mock request and response objects should look like. I strongly recommend to test locally before deploying to the Firebase cloud.</p>
<h3 id="deploying">Deploying a function</h3>
<p>The deployment of your function is easily done by using this command:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase deploy --only functions</code></pre>
</div>
<p>The tool checks if the project has been set up correctly and is backed by a Firebase project in the cloud, then zips your project and uploads it. Finally it prints the URL at which your function can be accessed. </p>
<p>The <code class="preserve-code-formatting">deploy</code> tool also prints the URL to the project console. You can use the project console to see how often each of your functions was executed, to see the logs and to see the total number of invocations. Depending on your plan this might be important information for your billing.</p>
<p>For accessing the logs you might prefer the command line option:</p>
<div class="sourcecode">
<pre class="language-bash line-numbers"><code class="language-bash line-numbers">
firebase functions:log --only yourFunction</code></pre>
</div>
<p>The <code class="preserve-code-formatting">--only yourFunction</code> part limits the output to the lines that belong to this specific function. You can also omit this option, in which case you get all the logs.</p>
<h3 id="">Wrap up</h3>
<p>So with this, you should have a good understanding of what Cloud Functions for Firebase is and how to use it. And - very important - how to properly test the functions you deploy to the Firebase cloud.</p>
<p>I am going to use those functions in my upcoming tutorials about developing apps for the Google Assistant. But all in all they can be used wherever a stateless service makes sense. Depending on your workload and your use case, <a href="https://en.wikipedia.org/wiki/Serverless_computing">serverless computing</a> can be a very cost-effective solution since you pay exactly for what you need.</p>
<p>Until next time: Happy coding!</p>
<p>The post <a href="https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/">A Primer on Cloud Functions for Firebase</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/primer-cloud-functions-for-firebase/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Quick Intro Into Actions on Google</title>
		<link>https://www.grokkingandroid.com/actions-on-google-quick-intro/</link>
					<comments>https://www.grokkingandroid.com/actions-on-google-quick-intro/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Wed, 02 Aug 2017 06:33:40 +0000</pubDate>
				<category><![CDATA[Google Assistant]]></category>
		<category><![CDATA[Actions on Google]]></category>
		<category><![CDATA[api.ai]]></category>
		<category><![CDATA[Conversational Interfaces]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3667</guid>

					<description><![CDATA[<p>Google Home will finally be available in Germany on August, 8th and in France this week. I'm not aware of more announcements for other countries, but I hope and assume that availability will increase to many more countries as soon as possible.1) For me, though, getting my AIY kit was the day, I started getting [...]&#160;&#160;<a href="https://www.grokkingandroid.com/actions-on-google-quick-intro/">Continue Reading&#160;&#160;"Quick Intro Into Actions on Google"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/actions-on-google-quick-intro/">Quick Intro Into Actions on Google</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Google Home will finally be available in Germany on August, 8th and in France this week. I'm not aware of more announcements for other countries, but I hope and assume that availability will increase to many more countries as soon as possible.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_1');" onkeypress="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_1');" ><sup id="footnote_plugin_tooltip_3667_14_1" class="footnote_plugin_tooltip_text">1)</sup></a><span id="footnote_plugin_tooltip_text_3667_14_1" class="footnote_tooltip"></span></span> For me, though, getting my AIY kit was the day, I started getting interested in <a href="https://developers.google.com/actions/">developing with Actions on Google</a>.</p>
<figure id="attachment_3682" aria-describedby="caption-attachment-3682" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/google_aiy.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/google_aiy-500x500.png" alt="Google&#039;s AIY kit" width="500" height="500" class="size-medium wp-image-3682" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/google_aiy-500x500.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/google_aiy-150x150.png 150w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/08/google_aiy.png 693w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3682" class="wp-caption-text">Google's AIY kit</figcaption></figure>
<h3>Different types of Interfaces</h3>
<p>Conversational interfaces is a very broad term. It covers all kind of chats whether voice is used or not up to pure voice interfaces like those used in Google Home.</p>
<p>Actions on Google supports text based interfaces - and depending on the capabilities of the devices - a limited set of visual feedback and touchable actions. I will cover those differences and how to detect which capabilities the device in question has, in later posts. On a mobile the text can be entered either by keyboard or by voice. With Google Home it obviously can only be entered by speaking to the device.</p>
<p>BTW: You can expect the assistant to appear in other devices as well. Be it IoT devices, cars or anything else where a voice interface can be useful. As you have seen in the first picture of this post, Google's AIY kit itself uses Actions on Google (or can be made to use it). How to achieve this is also the topic of an upcoming post.</p>
<h3>Two SDKs for The Google Assistant</h3>
<p>When it comes to the Google Assistant, there are two very different offerings by Google: </p>
<ul>
<li>The Assistant SDK and</li>
<li>Actions on Google</li>
</ul>
<h4>Assistant SDK</h4>
<p>With the <a href="https://developers.google.com/assistant/sdk/">Assistant SDK</a> you can enable devices to embed the Google Assistant. This means that it allows you to add the Google Assistant to a device made by you. It also allows you to change the way the Assistant is triggered on your device - for example you can use a button press instead of the "OK, Google" phrase. </p>
<p>The SDK is <a href="https://grpc.io/">gRPC</a> based, which is a protocol buffer based message exchange protocol. It has tons of bindings for a plethora of languages. As a sample (and for practical use as well) complete Python bindings for certain linux based architectures already exist.</p>
<p>If you are creating devices and want to integrate the Assistant into those, than the Assistant SDK is the SDK of your choice. The AIY kit, shown in the picture above, is running the Assistant SDK on a Raspberry Pi. I will get into this SDK in a follow-up post.</p>
<h4>Actions on Google</h4>
<p>With <a href="https://developers.google.com/actions/">Actions on Google</a> your can create apps for the Google Assistant. The remainder of this post is all about this option.</p>
<h3>Two options to use Actions on Google</h3>
<p>When developing apps for the Google Assistant, there too exist two options:</p>
<ul>
<li>Use the Actions SDK directly</li>
<li>Use a service on top of the Actions SDK</li>
</ul>
<p>Google gives you a recommendation as to when to use which option on its <a href="https://developers.google.com/actions/building-your-apps">"Build an app in 30 minutes"</a> guide.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_2');" onkeypress="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_2');" ><sup id="footnote_plugin_tooltip_3667_14_2" class="footnote_plugin_tooltip_text">2)</sup></a><span id="footnote_plugin_tooltip_text_3667_14_2" class="footnote_tooltip"></span></span></p>
<h4>Using the Actions SDK</h4>
<p>The Actions SDK allows you to directly access the recognized user text and to deal with it in your backend. It is suited for either very simple projects with clear commands or if you are sufficiently proficient in natural language processing.</p>
<p class="textbox"><strong>Edit (Oct. 12th, 2017):</strong> I have just published a detailled post about how to start <a href="https://www.grokkingandroid.com/using-the-actions-sdk/">developing apps for the Google Assistant using the Actions SDK</a>.</p>
<h4>Using api.ai or other services on top of the Actions SDK</h4>
<p>Most often using a service is the better option. It's not that the Actions SDK itself is particularly complex. The problem lies more in how to detect what the user intends with his response and how to parse the text to get relevant data. This is where those services shine. You enter some sample responses by the user and the services then not only understands these sentences but many, many more that resemble those sentences but use different wording, a different word order or a combination of both. And they extract the data you need in an easily accessible format. Consider understanding dates - which is not even the most complex example. You have to understand "next week", a specific date given, abbreviations, omissions and many more. That's the real value of these services.</p>
<p>One such service is <a href="https://dialogflow.com/">api.ai</a> which was bought by Google last fall. As such it's only natural that this service supports Actions on Google quite nicely. In addition to this you can use api.ai also for other platforms like Alexa, Cortana, Facebook Messenger and many more. I will cover api.ai thoroughly in future posts.</p>
<p class="textbox"><strong>Edit (Oct. 10th, 2017):</strong> As of today api.ai has been renamed to Dialogflow. The domain has also changed from api.ai to <a href="https://dialogflow.com/">dialogflow.com</a>.</p>
<p>You are not limited to api.ai, though. One contender is <a href="http://www.converse.ai/index.html">converse.ai</a> which I haven't had the opportunity to test, yet. The visual design of converse.ai's conversation flow has some appeal but whether it's practical and overall as good as api.ai, I cannot tell. But hopefully I will be able to evaluate it while continuing with my Actions on Google posts.</p>
<h3>Let's put things into perspective</h3>
<p>Even though conversational interfaces seem to be all the rage lately, they are not really new. </p>
<p>Actually they are quite old. <a href="https://en.wikipedia.org/wiki/ELIZA">Eliza</a> was programmed by Joseph Weizenbaum in the sixties and created quite a stir back then. You can <a href="http://www.masswerk.at/elizabot/eliza.html">try it out</a> on dozens on websites for yourself. </p>
<p>My first experience was the fictional interface shown in the film Wargames, 1983: You can see the part where this screenshot is taken from on <a href="https://www.youtube.com/watch?v=KXzNo0vR_dU">YouTube</a>.<span class="footnote_referrer"><a role="button" tabindex="0" onclick="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_3');" onkeypress="footnote_moveToReference_3667_14('footnote_plugin_reference_3667_14_3');" ><sup id="footnote_plugin_tooltip_3667_14_3" class="footnote_plugin_tooltip_text">3)</sup></a><span id="footnote_plugin_tooltip_text_3667_14_3" class="footnote_tooltip"></span></span></p>
<figure id="attachment_3668" aria-describedby="caption-attachment-3668" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog-500x467.png" alt="Chatbot of the eighties" width="500" height="467" class="size-medium wp-image-3668" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog-500x467.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog-768x718.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog-700x654.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/wargames_dialog.png 1027w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3668" class="wp-caption-text">A screenshot of a Wargames scene (1983)</figcaption></figure>
<p>And of course there was Clippy in the late nineties, the worst assistant ever:</p>
<figure id="attachment_3670" aria-describedby="caption-attachment-3670" style="width: 249px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/clippy.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/07/clippy.png" alt="Microsoft&#039;s Clippy" width="249" height="485" class="size-full wp-image-3670" /></a><figcaption id="caption-attachment-3670" class="wp-caption-text">Microsoft's Clippy</figcaption></figure>
<p>So if they are not new, why then <em>are</em> they all the rage? Well, luckily we have progressed from there on and nowadays we have all kind of chatbots integrated into messengers and other communication tools, we have website assistants that pop up if we ponder for a while on a particular page and we have true voice only interfaces like Amazon's Alexa and Google Home.</p>
<p>And those are powered by a much better understanding of human language, of the intents of the user and how to find and combine important entities of the user's spoken text.</p>
<p>The Google assistant works for voice only devices (like Google Home) or with some visual add ons on phones or other devices with a touchscreen.</p>
<h3>Wrap up</h3>
<p>This was a very quick rundown of the Actions on Google options. In coming posts I am going to show you the base concepts like actions, intents and fulfillment, how to make use of api.ai / Dialogflow, what tools and libraries Google provides, how to connect to your home devices, what permissions are needed for within the Assistant and how to make use of the Assistant from within Android Things.</p>
<p>And in the meantime I'm going to talk about this stuff on upcoming devfests <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Stay tuned! </p>
<div class="speaker-mute footnotes_reference_container"> <div class="footnote_container_prepare"><p><span role="button" tabindex="0" class="footnote_reference_container_label pointer" onclick="footnote_expand_collapse_reference_container_3667_14();">Footnotes</span><span role="button" tabindex="0" class="footnote_reference_container_collapse_button" style="display: none;" onclick="footnote_expand_collapse_reference_container_3667_14();">[<a id="footnote_reference_container_collapse_button_3667_14">+</a>]</span></p></div> <div id="footnote_references_container_3667_14" style=""><table class="footnotes_table footnote-reference-container"><caption class="accessibility">Footnotes</caption> <tbody> 

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_3667_14('footnote_plugin_tooltip_3667_14_1');"><a id="footnote_plugin_reference_3667_14_1" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>1</a></th> <td class="footnote_plugin_text">Right now it's available in the US, Canada, UK, France, Japan and Germany. But there's still a lot of place for improvement. Really, Google, you have to move faster when it comes to international rollouts!</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_3667_14('footnote_plugin_tooltip_3667_14_2');"><a id="footnote_plugin_reference_3667_14_2" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>2</a></th> <td class="footnote_plugin_text">30 mins? Seriously? This reminds me of those infamous "Teach yourself Java in 24 hours" book series. Never liked these titles!</td></tr>

<tr class="footnotes_plugin_reference_row"> <th scope="row" class="footnote_plugin_index_combi pointer"  onclick="footnote_moveToAnchor_3667_14('footnote_plugin_tooltip_3667_14_3');"><a id="footnote_plugin_reference_3667_14_3" class="footnote_backlink"><span class="footnote_index_arrow">&#8593;</span>3</a></th> <td class="footnote_plugin_text">Okay, those were the eighties, so it might feel strange to most of you <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /><br />
 </td></tr>

 </tbody> </table> </div></div><script type="text/javascript"> function footnote_expand_reference_container_3667_14() { jQuery('#footnote_references_container_3667_14').show(); jQuery('#footnote_reference_container_collapse_button_3667_14').text('−'); } function footnote_collapse_reference_container_3667_14() { jQuery('#footnote_references_container_3667_14').hide(); jQuery('#footnote_reference_container_collapse_button_3667_14').text('+'); } function footnote_expand_collapse_reference_container_3667_14() { if (jQuery('#footnote_references_container_3667_14').is(':hidden')) { footnote_expand_reference_container_3667_14(); } else { footnote_collapse_reference_container_3667_14(); } } function footnote_moveToReference_3667_14(p_str_TargetID) { footnote_expand_reference_container_3667_14(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } } function footnote_moveToAnchor_3667_14(p_str_TargetID) { footnote_expand_reference_container_3667_14(); var l_obj_Target = jQuery('#' + p_str_TargetID); if (l_obj_Target.length) { jQuery( 'html, body' ).delay( 0 ); jQuery('html, body').animate({ scrollTop: l_obj_Target.offset().top - window.innerHeight * 0.2 }, 380); } }</script><p>The post <a href="https://www.grokkingandroid.com/actions-on-google-quick-intro/">Quick Intro Into Actions on Google</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/actions-on-google-quick-intro/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Android Things: Remote Controlled Car &#8211; What&#8217;s Coming Up</title>
		<link>https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/</link>
					<comments>https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 09 Feb 2017 05:41:34 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android Things]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3644</guid>

					<description><![CDATA[<p>Being an Android Developer, Google's announcement of Android Things immediately piqued my interest. As all the others I started out with buying one of the developer kits and then making some lights blink. Nice. But, well, if I have to be honest with myself, that was fun but actually of only limited use 🙂 &#160;Then [...]&#160;&#160;<a href="https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/">Continue Reading&#160;&#160;"Android Things: Remote Controlled Car &#8211; What&#8217;s Coming Up"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/">Android Things: Remote Controlled Car &#8211; What&#8217;s Coming Up</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Being an Android Developer, Google's announcement of <a href="https://developer.android.com/things/index.html">Android Things</a> immediately piqued my interest.</p>
<p>As all the others I started out with buying <a href="https://developer.android.com/things/hardware/developer-kits.html">one of the developer kits</a> and then making some lights blink. Nice. But, well, if I have to be honest with myself, that was fun but actually of only limited use <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> &nbsp;Then again, fun is why I started out coding, so maybe not so limited after all.</p>
<p>Still, as I nevertheless wanted to create something more useful, now came the hard part: What to actually create? What could keep me going? </p>
<p>Since my kids obviously play a huge role in my life, I used it to <a href="https://twitter.com/i/videos/tweet/815675104420134912">play "Happy birthday" and "Auld Lang Syne"</a> on my son's birthday (which incidentally is on January, 1st) next. Better, but given the dismal sound quality, still not good enough.</p>
<p>After some googling around, skimming makers books at the local library and looking at <a href="https://www.adafruit.com/">Adafruit's</a> (US), <a href="https://shop.pimoroni.com/">Pimoroni's</a> (UK), <a href="https://www.kiwi-electronics.nl/">Kiwi Electronic's</a> (NL) and <a href="https://www.flikto.de/">Flikto Elektronik's</a> (D) websites, I decided to do some kind of vehicle. I thought, that's something that also might get the attention of my kids - and after showing them some pics on the web, they indeed agreed: That's the thing to go forward with.</p>
<h3>First idea</h3>
<p>The first idea was to use a ready made kit. This kit would provide all the necessary hardware like motors, motor drivers, wheels and so on. The only exception would be the Raspberry Pi (the developer board I chose to buy) itself.</p>
<p>That's nice enough and proved to be quite a good starting point. But then I <a href="http://de.engadget.com/2014/01/27/diy-lego-rc-mit-raspberry-pi/">saw</a> <a href="http://raspivan.weebly.com/rasppicar.html">more</a> <a href="http://mattandshirl.blogspot.de/2013/06/lego-car-controlled-by-raspberry-pi-and.html">self-made</a> <a href="https://github.com/jtyr/legoirc-server">ideas</a>. Having to build more ourselves is much better suited for us as a family. Especially since it gives the kids much more space to contribute to the overall project. For some nice pics see this <a href="https://www.google.de/search?q=lego+car+raspberry+pi&amp;tbm=isch&amp;tbo=u">Google image search for "Lego car raspberry pi"</a>.</p>
<p>This <a href="http://custom-build-robots.com/robot-cars/rc-car-build-of-lego-bricks-with-raspberry-pi/5">car with Lego</a> looked pretty impressive. Since the kids love to build and rebuild stuff with Lego this project of a Lego&trade; chassis is the role-model for our project. The kids could build (and rebuild) the chassis. They could also help connect some parts of the electronics. My role would be limited to ordering (and paying for) the stuff, soldering a bit (I <strong>hate</strong> soldering and try to get around it as much as possible) and, obviously, coding the apps.</p>
<p>To quickly get a grasp of what the coding might involve, I still bought a complete kit <a href="https://shop.pimoroni.com/products/sts-pi">(the STS-PI by Pimoroni)</a> as some kind of MVP for our RC car. As you can see it's a rather simple construction - which suited me for getting started.</p>
<figure id="attachment_3654" aria-describedby="caption-attachment-3654" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/STS-PI.jpg"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/STS-PI-500x375.jpg" alt="The STS-PI already assembled by us" width="500" height="375" class="size-medium wp-image-3654" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/STS-PI-500x375.jpg 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/STS-PI-768x576.jpg 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/STS-PI-700x525.jpg 700w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3654" class="wp-caption-text">The STS-PI already assembled by us</figcaption></figure>
<p>But it was obvious from the beginning that this would only be a start to test out some stuff and that the real thing would come later. </p>
<figure id="attachment_3656" aria-describedby="caption-attachment-3656" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/wheel_attached_to_motor.jpg"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/wheel_attached_to_motor-500x375.jpg" alt="One of the wheels of the final car attached to a motor" width="500" height="375" class="size-medium wp-image-3656" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/wheel_attached_to_motor-500x375.jpg 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/wheel_attached_to_motor-768x576.jpg 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/wheel_attached_to_motor-700x525.jpg 700w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3656" class="wp-caption-text">One of the wheels of the final car attached to a motor</figcaption></figure>
<p>In the following sections I'm roughly outlining some thoughts about the project so far - and some of the decisions already made.</p>
<h3>Battery or cable</h3>
<p>Actually that's no question. The raspberry will be mounted on the chassis and the car must function without being tethered to any power plug or - even worse - my developer laptop. So I'm going to use a battery. For the quick prototype it will simply be a power bank. For the final thing it's going to be proper batteries that are powerful enough to power the more powerful motors of the final car as well as the Raspberry Pi.</p>
<h3>Controlling the car</h3>
<p>First explorations revealed that both Bluetooth and <a href="https://developer.android.com/guide/topics/connectivity/wifip2p.html">Wifi Peer to Peer</a> are not available on Android Things, yet. I very much hope they will be supported soon! </p>
<p>Building a proper radio controller is beyond my beginner's grasp of hardware related stuff - and it surely doesn't follow the minimum viable product approach. My kids (and I!) want to see a car going - no need to wait needlessly long <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Thus I am going to use Wifi where both the car and the remote controller handheld are in the same network. But if I am going to use <a href="https://developer.android.com/training/connect-devices-wirelessly/nsd.html">DNS-SD</a> I have not yet decided - nor do I know if this works on Android Things.</p>
<p>Since I might eventually change to some kind of radio controller, the app must be flexible enough to accommodate for this change.</p>
<h3>Abstracting the car</h3>
<p>I already mentioned that I have a kit for quickly getting to first results and that we later on want to built a car with Lego. Not sure how much they will differ in the end, but it's very <em>likely</em> that they will have differing characteristics. My remote control shouldn't need to know about this - and ideally most of the app on the car neither.  </p>
<h3>Abstracting the device</h3>
<p>Android Things runs on multiple devices. There are three developer kits already available and two currently listed as coming soon. And I expect more to come. Even though I currently only own two Raspberry Pi boards, I want this project to be agnostic to the actual device the car is running on. Thus I will also abstract away some of the Android Things characteristics. </p>
<h3>Family requirements</h3>
<p>We have two kids and thus have to have two vehicles (or suffer endless bickering). That one's easy: We will have the Pimoroni kit and the self-built one.</p>
<p>For the same reason both cars must be usable at the same time. Which has some ramifications for the apps. The remote controls must be able to steer both cars. But of course only one at a time. Maybe we even need some parental mode to prevent the kids switching cars on their own and thereby annoying the other one. You have no idea how big a role conflict prevention plays in my daily family life <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f600.png" alt="😀" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Preliminary requirements</h3>
<p>To start with, these are the project's requirements. They will evolve and be adapted while going along and I expect more to be appended. But for now those are the basics:</p>
<ul>
<li>The system must support multiple cars</li>
<li>The system must support multiple Android handhelds as remote controls</li>
<li>The system must support different Android Things devices to be used within the vehicles</li>
</ul>
<h3>Next steps</h3>
<p>The first item going to be implemented will be to make the Pimoroni kit move properly - while keeping the abstractions in mind. At first it will just run a preprogrammed sequence to showcase that the car can go forward, backward and can turn around.</p>
<p>I haven't decided yet about the next steps after this, but most likely I will first create the remote control before building the second car. But with the kids acting like product owners, you never know.</p>
<p>BTW: Some preparations have already been done:</p>
<p>We ordered a <a href="https://www.roboter-bausatz.de/143/l298n-motortreiber-mit-doppelter-h-bruecke">motor driver</a>. We ordered some <a href="https://www.roboter-bausatz.de/460/roboter/auto-reifen-inkl.-getriebemotor-1-48">wheels and motors</a> and I even soldered some wires onto them. We ordered some <a href="http://www.brick-shop.de/product_info.php/info/p5135_technic-stein-1x4-blau--3701-.html">Lego bricks</a> <a href="http://www.brick-shop.de/product_info.php/info/p5100_technic-1x2-gelb--3700-.html">with holes</a> to fasten the motor properly. Alas, those Lego parts are not here, yet. Which means we cannot start constructing the chassis <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>But apart from that, not much has been done yet. I guess it's about time to get my hands dirty and to start coding.</p>
<p>Stay tuned! You will hear about our progress.</p>
<p>And in the meantime: Keep coding! Keep tinkering!</p>
<figure id="attachment_3655" aria-describedby="caption-attachment-3655" style="width: 375px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/motor_with_very_professional-cough-soldering.jpg"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/motor_with_very_professional-cough-soldering-375x500.jpg" alt="The motors complete with soldered-on wire" width="375" height="500" class="size-medium wp-image-3655" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/motor_with_very_professional-cough-soldering-375x500.jpg 375w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/motor_with_very_professional-cough-soldering-768x1024.jpg 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2017/02/motor_with_very_professional-cough-soldering-525x700.jpg 525w" sizes="auto, (max-width: 375px) 100vw, 375px" /></a><figcaption id="caption-attachment-3655" class="wp-caption-text">The motors complete with soldered-on wire</figcaption></figure>
<p>
<small><br />
Lego&trade; is a trademark of The LEGO Group. Android&trade; is a trademark of Google.<br />
</small></p>
<p>The post <a href="https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/">Android Things: Remote Controlled Car &#8211; What&#8217;s Coming Up</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/android-things-remote-controlled-car-whats-coming-up/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Android&#8217;s ConstraintLayout: Align One View&#8217;s Edge to Another View&#8217;s Center</title>
		<link>https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/</link>
					<comments>https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 30 Aug 2016 07:20:07 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[ConstraintLayout]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3538</guid>

					<description><![CDATA[<p>As you can see from the following excerpt of ConstraintLayout&#039;s supported attributes, there is no layout_constraintStart_toCenterX attribute. Thus you cannot directly align the left edge of one view to the center of another view. But ConstraintLayout is flexible enough to get your view aligned to the center of another view without such an attribute. Even [...]&#160;&#160;<a href="https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/">Continue Reading&#160;&#160;"Android&#8217;s ConstraintLayout: Align One View&#8217;s Edge to Another View&#8217;s Center"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/">Android&#8217;s ConstraintLayout: Align One View&#8217;s Edge to Another View&#8217;s Center</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As you can see from the following excerpt of <code class="preserve-code-formatting">ConstraintLayout&#039;s</code> supported attributes, there is no <code class="preserve-code-formatting">layout_constraintStart_toCenterX</code> attribute. Thus you cannot directly align the left edge of one view to the center of another view.</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;attr name=&quot;layout_constraintLeft_toLeftOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintLeft_toRightOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintRight_toLeftOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintRight_toRightOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintTop_toTopOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintTop_toBottomOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintBottom_toTopOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintBottom_toBottomOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintBaseline_toBaselineOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintStart_toEndOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintStart_toStartOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintEnd_toStartOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;
&lt;attr name=&quot;layout_constraintEnd_toEndOf&quot; format=&quot;reference|enum&quot;&gt;...&lt;/attr&gt;</code></pre>
</div>
<p>
But <code class="preserve-code-formatting">ConstraintLayout</code> is flexible enough to get your view aligned to the center of another view without such an attribute. Even though the solutions is a tad hacky <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Say you have view A and want another view B to left-align to the center of A. To achieve this you can add yet another view C. Align both edges of C to the respective edges of A. C is thus centered to A. Now you can align the left edge of B to the right edge of C. Finally set the visibility of the helper view C to <code class="preserve-code-formatting">View.GONE</code> - and you are done.</p>
<p>Here's the screen showing it before the view is set to <code class="preserve-code-formatting">View.GONE</code>:</p>
<figure id="attachment_3552" aria-describedby="caption-attachment-3552" style="width: 700px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_-700x414.png" alt="Left align a view to the center of another view within Android's Constraintlayout - how it looks before the helper view is marked GONE" width="700" height="414" class="size-large wp-image-3552" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_-700x414.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_-500x295.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_-768x454.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_before_view.gone_.png 963w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a><figcaption id="caption-attachment-3552" class="wp-caption-text">Left align a view to the center of another view - how it looks before the helper view is marked GONE</figcaption></figure>
<p>And this is the desired result after setting the helper view to <code class="preserve-code-formatting">View.GONE</code>:</p>
<figure id="attachment_3553" aria-describedby="caption-attachment-3553" style="width: 700px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version-700x414.png" alt="The final result of a view appearing to be left aligned to the center of another view when using ConstraintLayout" width="700" height="414" class="size-large wp-image-3553" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version-700x414.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version-500x296.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version-768x454.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version.png 961w" sizes="auto, (max-width: 700px) 100vw, 700px" /></a><figcaption id="caption-attachment-3553" class="wp-caption-text">The final result of a view appearing to be left aligned to the center of another view</figcaption></figure>
<p>Have a look at <a href="https://gist.github.com/writtmeyer/f5971266394b2316eb01b566cdeff2a0" title="The XML of the final layout file">this gist of the actual layout file</a>. It probably makes the steps more obvious.</p>
<p><strong>Keep in mind:</strong> You cannot use a view and simply set it's <code class="preserve-code-formatting">layout_width</code> and <code class="preserve-code-formatting">layout_height</code> to <code class="preserve-code-formatting">0dp</code> - since this is equivalent to stretching within a <code class="preserve-code-formatting">ConstraintLayout</code>. To make a view have a height and width of zero, you have to set it's visibility to GONE. That's the only way to achieve this!</p>
<p>I think I mentioned it already in my previous <code class="preserve-code-formatting">ConstraintLayout</code> article. But maybe it's time to repeat myself: I really like what Google's devs are doing with ConstraintLayout. Keep up the good work <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p><meta name="twitter:image" content="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/08/left_align_to_center_final_version.png" /></p>
<p>The post <a href="https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/">Android&#8217;s ConstraintLayout: Align One View&#8217;s Edge to Another View&#8217;s Center</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/align-one-views-edge-to-another-views-center-in-constraintlayout/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Some Thoughts on Android&#8217;s new ConstraintLayout and Android Studio&#8217;s new Design Editor</title>
		<link>https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/</link>
					<comments>https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Wed, 06 Jul 2016 06:10:42 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android Studio]]></category>
		<category><![CDATA[ConstraintLayout]]></category>
		<category><![CDATA[Layout Editor]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3435</guid>

					<description><![CDATA[<p>At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped layout editor. I am not going into how to use the layout. Google itself has done a good job in explaining it with its code lab "Using ConstraintLayout to design your views". In this post I [...]&#160;&#160;<a href="https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/">Continue Reading&#160;&#160;"Some Thoughts on Android&#8217;s new ConstraintLayout and Android Studio&#8217;s new Design Editor"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/">Some Thoughts on Android&#8217;s new ConstraintLayout and Android Studio&#8217;s new Design Editor</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped layout editor. I am not going into how to use the layout. Google itself has done a good job in explaining it with its code lab <a href="https://codelabs.developers.google.com/codelabs/constraint-layout/index.html" title="Google's code lab about the new ConstraintLayout">"Using ConstraintLayout to design your views"</a>.</p>
<p>In this post I am going to highlight what I like about the new layout and the new editor. </p>
<h3>What's to like about the new ConstraintLayout</h3>
<p>With the new layout there's a lot to like. Here are my favorite things about it:</p>
<ul>
<li>The aim to help us developers</li>
<li>The availability of the stretched width/height of its children</li>
<li>The use of guidelines</li>
<li>The fact that is doesn't feel as weird as Auto Layout</li>
</ul>
<p>Now let me dig a bit more into each of these.</p>
<h4>The aim to help us developers</h4>
<p>At this years Google IO talk <a href="https://www.youtube.com/watch?v=sO9aX87hq9c">"Android Layouts: a new world"</a>&ensp;<a href="https://plus.google.com/+NicolasRoard">Nicolas Roard</a>&ensp;and&ensp;<a href="https://plus.google.com/+JohnHoford/">John Hoford</a>&ensp;gave two reasons for introducing a new layout:</p>
<ul>
<li>To make handling complex screen designs easier</li>
<li>To improve the performance of complex layouts</li>
</ul>
<p>And both are, of course, highly appreciated. </p>
<p>If you have a complex layout, things can get pretty difficult to manage. Moving stuff around in a <code class="preserve-code-formatting">RelativeLayout</code> is bound to break a lot of other stuff. That's what they cited at IO. And it is true. So if this new layout help us with this, I'm all for it.</p>
<p>On the other hand things are currently not as bad, as they made them out to be. And the nesting can actually help you understand certain parts of the layout better since they are grouped and broken down into smaller parts. More practice with the new layout will show, if this really makes that much of a difference when maintaining screens.</p>
<p>In my opinion more important is the second motivation: To improve the performance. As users we all want the apps on our devices to run as smoothly as possible. And as developers we want to deliver this experience to our users. Thus, I'm all for it. </p>
<p>When it comes to performance improvements there is never any limit for additional improvements. So if Google helps us, I'm more than happy. Maybe this way the <code class="preserve-code-formatting">ConstraintLayout</code> also reduces the need for some custom views or layouts.</p>
<p>A bit down I'm going to have a look at the actual performance of the <code class="preserve-code-formatting">ConstraintLayout</code> <em>as it is today</em>. It definitely needs more work. But the goal is laudable and the final implementation surely will fare much better than the current one. Mind you, we are talking about an alpha version here!</p>
<h4>The availability of the stretched width/height of its children</h4>
<p>The new stretched (or "any size") appearance is better than <code class="preserve-code-formatting">match_parent</code> in the context of this new layout. By stretching to it's constraints this new mode is not limited to the enclosing container but can be used for arbitrary areas of the screen. You could achieve this with other means before - but now we have a unified concept for everything, which sounds more logical to me. It's not that big a change, but a nice one nonetheless.</p>
<h4>Guidelines are great additions</h4>
<p>In addition to the layout and the editor we also have guidelines. These only make sense in the context of the <code class="preserve-code-formatting">ConstraintLayout</code> - but they are actually proper views. They show up as separate view items in the hierarchy and get rendered at runtime.</p>
<p>But fear not. The decompiled Guildeline class is not only a mere 44 lines short - it also is as simple as a view can get. It doesn't draw anything, always sets the dimension to zero width and zero height in its <code class="preserve-code-formatting">onMeasure()</code> method and on top of that sets itself to <code class="preserve-code-formatting">View.GONE</code> in the constructors. So no problems here. </p>
<p>What this means is, that the guidelines can work as any other view, when it comes to constraints.</p>
<p>For the placement of the guidelines you can use fixed values (say always 100 dp from the left edge) or percent values (say always at 33% of the whole screen width).</p>
<p>Later on in this post I am going to show you a sample for how to make good use of guidelines.</p>
<h4>Not as weird as Auto Layout</h4>
<p>When I first heard about the new layout during the IO keynote, my first thought was: "Oh no! Auto Layout is coming". I have not done much with iOS, but what I have seen of Auto Layout, well, let's put it this way: I do not necessarily like it. It breaks to easily whenever you try to do something with the screen. It's only partially intuitive. In short it's nothing you <em>like</em> to work with. </p>
<p>Right now I do not have these negative thoughts when it comes to <code class="preserve-code-formatting">ConstraintLayout</code>. Maybe Google learned something from what Apple did wrong. But it could as well be, that it's just because <code class="preserve-code-formatting">ConstraintLayout</code> is not (yet?) as powerful as Auto Layout. I don't know - all I can say is, that <code class="preserve-code-formatting">ConstraintLayout</code> seems to behave quite reasonably. But seasoned iOS devs might think about this issue very differently <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>What's to like about the new editor?</h3>
<p>The new editor of course is also part of Google's plans to make life for us developers easier. Actually it might end up to be also quite useful for sketching and prototyping. Who knows.</p>
<p>I especially like these things:</p>
<ul>
<li>The properties pane has improved a lot</li>
<li>The editor shows lint warnings and errors prominently</li>
<li>The editor supports all kind of <code class="preserve-code-formatting">ViewGroups</code> - not only <code class="preserve-code-formatting">ConstraintLayout</code></li>
<li>Everything is still XML backed</li>
<li>The screen is easily resizeable</li>
<li>The editor lets you select an image for all <code class="preserve-code-formatting">ImageViews</code> right away</li>
</ul>
<h4>The improved properties pane</h4>
<p>Do you remember the old properties pane? All kind of attributes were listed in an alphabetical way. Only very few more important properties were at the top:</p>
<figure id="attachment_3503" aria-describedby="caption-attachment-3503" style="width: 258px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/old_properties_pane.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/old_properties_pane-258x500.png" alt="The properties pane of the old layout editor" width="258" height="500" class="size-medium wp-image-3503" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/old_properties_pane-258x500.png 258w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/old_properties_pane.png 316w" sizes="auto, (max-width: 258px) 100vw, 258px" /></a><figcaption id="caption-attachment-3503" class="wp-caption-text">The properties pane of the old layout editor</figcaption></figure>
<p>Now this has changed significantly - and it is much more usable that way:</p>
<figure id="attachment_3504" aria-describedby="caption-attachment-3504" style="width: 257px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/new_properties_pane.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/new_properties_pane-257x500.png" alt="The properties pane of the new layout editor" width="257" height="500" class="size-medium wp-image-3504" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/new_properties_pane-257x500.png 257w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/new_properties_pane.png 360w" sizes="auto, (max-width: 257px) 100vw, 257px" /></a><figcaption id="caption-attachment-3504" class="wp-caption-text">The properties pane of the new layout editor</figcaption></figure>
<p>Android Studio by default lists only important and often used properties in this pane. Though, if you feel like it, you can always go back to the old list by clicking on the &quot;Show expert properties&quot; button on the top right.</p>
<p>Some attributes probably should be added (like <code class="preserve-code-formatting">layout_weight</code> for <code class="preserve-code-formatting">LinearLayout</code> children or <code class="preserve-code-formatting">layout_gravity</code>), but all in all this is much better than before.</p>
<p>Also note that for views that extend other views the properties pane lists the properties grouped by the class they originate from. In this case first those of <code class="preserve-code-formatting">Button</code> and afterwards those of the inherited <code class="preserve-code-formatting">TextView</code>.</p>
<h4>The error hints</h4>
<p>Another nice addition we haven't had before is the prominent display of lint errors and warnings in glaring red, so that you can't miss them:</p>
<figure id="attachment_3491" aria-describedby="caption-attachment-3491" style="width: 208px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/lint_errors_and_wrnings.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/lint_errors_and_wrnings.png" alt="Indicator showing that the layout contains problems" width="208" height="107" class="size-full wp-image-3491" /></a><figcaption id="caption-attachment-3491" class="wp-caption-text">Indicator showing that the layout contains problems</figcaption></figure>
<p>And if you click on the number, it expands to show the problems:</p>
<figure id="attachment_3492" aria-describedby="caption-attachment-3492" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors-500x364.png" alt="Popup showing details about the problems" width="500" height="364" class="size-medium wp-image-3492" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors-500x364.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors-768x559.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors-700x509.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/details_about_errors.png 881w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3492" class="wp-caption-text">Popup showing details about the problems</figcaption></figure>
<p>And as you can see, it also shows the content of the view in question, so that you know right away which view has a problem. Nice!</p>
<h4>The new editor supports all kind of ViewGroups</h4>
<p>When Google introduced the new layout editor it only showed it with the <code class="preserve-code-formatting">ConstraintLayout</code>. But you will be able to use it for all existing layouts as well. For <code class="preserve-code-formatting">Linearlayout</code> this works well, for <code class="preserve-code-formatting">RelativeLayout</code> not so much. For <code class="preserve-code-formatting">RelativeLayout</code> some magic of the <code class="preserve-code-formatting">ConstraintLayout</code> like dragging to which other view the new view should be relative to would make sense as well.</p>
<p>I guess Google puts more emphasis on correctly supporting <code class="preserve-code-formatting">ConstraintLayout</code> than supporting the other layouts like <code class="preserve-code-formatting">RelativeLayout</code>. Actually: I hope so. I very rarely used the designer with those older layouts. I preferred the XML view and expect this to remain unchanged for those. And for those "legacy" <code class="preserve-code-formatting">ViewGroup</code> types I wouldn't mind if it stayed like that. After all the idea is to get rid of them anyway.</p>
<h4>Everything is still XML backed</h4>
<p>Obviously the aim of Google is for us to use the layout editor instead of the XML editor in the future. So why then is XML still a big deal?</p>
<p>In my opinion there are a few reasons:</p>
<ul>
<li><strong>XML is better to fix fiddly things</strong><br />
Sometimes working with a graphical editor has its drawbacks and it can become pretty difficult to access the correct handle and drag it onto the correct drop target. Or you made a mistake and marked some views as invisible or gone - or made them ridiculously small.</li>
<li><strong>XML is ideal for version control</strong><br />
With a simple diff you can quickly see what changed over time. This is nice for yourself (using your local history or comparing changes to previous versions). But is even more important when collaborating with other. Code reviews and reasoning and discussing about pull requests is so much easier with XML and line numbers than having to throw screenshots around or having to run stuff just to understand even the simplest changes.
</li>
</ul>
<p></p>
<h4>Easy resizability of screen</h4>
<p>At the bottom right corner of the screen you have this handle. Nearly too unobstrusive:</p>
<figure id="attachment_3494" aria-describedby="caption-attachment-3494" style="width: 73px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/resize_handle.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/resize_handle.png" alt="Resize handle at the bottom right corner" width="73" height="71" class="size-full wp-image-3494" /></a><figcaption id="caption-attachment-3494" class="wp-caption-text">Resize handle at the bottom right corner</figcaption></figure>
<p>You can use this handle to drag and resize the current preview screen and see which influence this has on your layout. Probably not often needed, but it can come in handy - while creating your layout, but also during presentations and trainings.</p>
<h4>The editor lets you select an image for all ImageViews right away</h4>
<p>Whenever you drag an <code class="preserve-code-formatting">ImageView</code> or <code class="preserve-code-formatting">ImageButton</code> onto the layout, the editor pops open a dialog in which you can choose the image to show or the color to use. That might not save <em>that much</em> work, but it's still a nice detail, that I appreciate:</p>
<figure id="attachment_3497" aria-describedby="caption-attachment-3497" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/image_selection.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/image_selection-500x484.png" alt="Dialog for image selection" width="500" height="484" class="size-medium wp-image-3497" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/image_selection-500x484.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/image_selection-700x678.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/image_selection.png 717w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3497" class="wp-caption-text">Dialog for image selection</figcaption></figure>
<p>Note that this screen also shows the more likely ones (the images of your project) at the top.</p>
<h3>What about Performance?</h3>
<p>Since performance improvements are among the main reasons to create this new layout, I did some performance tests to check if this goal is met.</p>
<p>I compared a layout used within a <code class="preserve-code-formatting">RecyclerView</code>. Nothing too fancy, just some nested <code class="preserve-code-formatting">LinearLayout</code> and <code class="preserve-code-formatting">RelativeLayout</code> containers. I moved this layout manually over to <code class="preserve-code-formatting">ConstraintLayout</code> and did some rather sloppy performance tests.</p>
<p>Comparing those two on an emulator as well as on an Nexus 5 yielded overall a performance penalty when using the new <code class="preserve-code-formatting">ConstraintLayout</code>.</p>
<p>Performing worst is the measurement. The <code class="preserve-code-formatting">onMeasure()</code> method takes roughly ten times as long as the one of the <code class="preserve-code-formatting">LinearLayout</code> I used for comparison. And it uses up the bulk of the time with taking about 60 times as long as <code class="preserve-code-formatting">onLayout()</code>. Thus the 30 per cent hit of the <code class="preserve-code-formatting">onLayout()</code> method of <code class="preserve-code-formatting">ConstraintLayout</code> compared to the one of the <code class="preserve-code-formatting">LinearLayout</code> in question is nearly irrelevant. Finally layout inflation also took longer with <code class="preserve-code-formatting">ConstraintLayout</code> than with <code class="preserve-code-formatting">LinearLayout</code>.</p>
<p>The <code class="preserve-code-formatting">ConstraintLayout</code> does lots of calculations to find out where and how to display each of its children. Internally (at least) three rather lengthy classes are working together to get the results: <code class="preserve-code-formatting">LinearSystem</code>, <code class="preserve-code-formatting">ConstraintWidget</code> and <code class="preserve-code-formatting">ConstraintWidgetContainer</code>. To fully understand the performance behaviour I would have to dig into the depth of these classes (and for this I prefer the commented classes when their sources are released by Google). But just by having a cursory look at the decompiled code it looks like those classes have to do <em>a lot</em>. </p>
<p>Right now it looks like the performance improvements that Google hopes to achieve are far off. But at the Google IO talk John and Nicolas mentioned that they are working hard on improving the performance. So we can expect this to get better over time. And since the <code class="preserve-code-formatting">ConstraintLayout</code> comes as a separate library, further improvements are likely even <em>after</em> the final release. If the result will be good enough in the end - well, that remains to be seen. We have to wait for future releases. And we have to do some more (and more thorough) testing with multiple layouts. Right now I'm more than willing to give Google the benefit of the doubt.</p>
<p><strong>Additional note (as of July, 9th):</strong> This post was written based on the third alpha of <code class="preserve-code-formatting">ConstraintLayout</code>. In the meantime a fourth has been released. Which, <a href="https://twitter.com/camaelon/status/751697785053966336">according to Nicolas Rouard</a>, should be performing much better. I will give it a try and let you know about improvements in future posts. As I've written above: Google is hard at work on improving performance - and even this fourth release is still an <em>alpha</em> release!</p>
<p><strong>Additional note (as of July, 22th):</strong> I have used the same layout for testing the fourth alpha build. It is indeed much better - but still needs improvements. With the performance imporvements of this build, <code class="preserve-code-formatting">onLayout()</code> takes roughly a third of the time it took before. And <code class="preserve-code-formatting">onMeasure()</code> now roughly twice as fast as before.</p>
<p>In one thread on twitter, <a href="https://twitter.com/camaelon/status/751713544781967360">Nicolas Rouard mentioned</a> that - performancewise - <code class="preserve-code-formatting">ConstraintLayout</code> is best for complex layouts for which you would have needed deeply nested layouts before. Keep this in mind, when deciding what layout to use. If time allows, I will try to find a suitable deeply nested layout to verify this in future add-ons to this post.</p>
<h3>Some annoyances</h3>
<p>Not all is working perfectly at the moment, though. Right now these things bother me the most:</p>
<ul>
<li>There's a noticeable lag between blueprint changes and design preview changes</li>
<li>The preview is not always correct</li>
<li>The blueprint view doesn't heed text layout constraints</li>
<li>Constraints do not always work as expected</li>
<li>Undo works <strong>very</strong> unreliably</li>
<li>The editor undos stuff or changes stuff in unexpected ways</li>
</ul>
<h4>Noticable lag between blueprint changes and design preview changes</h4>
<p>On bigger screens it's quite useful to open the blueprint view and the preview next to each other. But especially if you use lots of stretched views or many views that make use of the bias you will notice a growing lag in the preview.</p>
<p>This has already improved a bit with the latest updates, but is still noticeable and sometimes a bit irritating. Also while calculating those new positions the editor makes heavy use of your CPU. Luckily only for short bursts.</p>
<h4>Preview is not always correct</h4>
<p>When you miss some constraints, the preview view shows an incorrect screen. This actually is by design and has been different in the very first version of the layout editor. Back then (due to the aforementioned lag) things jumped around seemingly haphazardly, which of course was very disturbing. But apart from the lag the other reason for this was, that you can use the preview to drag things around. Which I strongly advocate against (see below). There's no reason for that. We have the blueprint editor to edit constraints. Let the preview do what its name implies.</p>
<h4>Blueprint view doesn't heed text layout constraints</h4>
<p>This is a fairly minor issue - yet one I would like to see corrected. In a <code class="preserve-code-formatting">TextView</code> setting the gravity doesn't change the location of the text in the <em>blueprint</em> view. The setting is reflected correctly in the design preview, but when working with the blueprint only, it feels odd that changing this setting doesn't have any effect. Switching between the design and blueprint view just to verify that this setting did indeed work as expected is a bit cumbersome. Nothing that makes life really hard, but something that requires an extra step and makes one wonder at first.</p>
<h4>Constraints do not always work as expected</h4>
<p>The following screenshot admittedly show a very weird and pretty useless screen - but it shows that constraints might not work as you would expect them to work:</p>
<figure id="attachment_3506" aria-describedby="caption-attachment-3506" style="width: 286px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/totally_pointless_screen_showing_an_error.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/totally_pointless_screen_showing_an_error-286x500.png" alt="Screen showing constraints not working properly" width="286" height="500" class="size-medium wp-image-3506" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/totally_pointless_screen_showing_an_error-286x500.png 286w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/totally_pointless_screen_showing_an_error-401x700.png 401w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/totally_pointless_screen_showing_an_error.png 407w" sizes="auto, (max-width: 286px) 100vw, 286px" /></a><figcaption id="caption-attachment-3506" class="wp-caption-text">Screen showing constraints not working properly</figcaption></figure>
<p>Never mind that this screen is among the weirdest app screen you might ever stumble upon. It still should be correct <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>As you can see the bottom button is left aligned to the right button in the second row. That's at least how the button <em>should</em> be. And you can also see, that this button is stretched. So why then does it stretch that far to the left? What makes this calculation go <em>that</em> wrong? My guess is, that the problem is not so much with the button at the bottom, but the buttons of the second row.</p>
<p>What worries me is not that this specific screen isn't working. The problem is, that I do not know why it's not working and what makes views appear so wrongly aligned. As long as things like this can happen, you are bound to run into this problem with a real screen on a real device eventually. And <em>then</em> it is really bothersome.</p>
<h4>Undo works <strong>very</strong> unreliably</h4>
<p>On one screen I accidentally moved one view around <em>after</em> I set some button's visibility to gone and to visible again. I hit Ctrl-Z and the button's visibility changes to gone again. What I had expected, of course, was to undo the last step - which was the accidental dragging of another view.</p>
<p>Trying to reproduce exactly these steps for this post I was not only not able to reproduce this particular problem. Instead I was now not able to undo the moving around step. Alas, very unpredictable again.</p>
<p>One of the earlier versions also behaved differently when using Undo via the menu or hitting Ctrl-Z. This <em>appears</em> to be fixed in the current version. But since Undo is so unreliable in general I do not know for sure.</p>
<p><em><strong>I think this is the worst problems the editor has right now.</strong></em> When working graphically to quickly test stuff, moving items around should be easily - and reliably - reversible. Otherwise this editor hampers experimentation and is not useful for quickly sketching and for trying things out.</p>
<h4>The editor undos or changes stuff in unexpected ways</h4>
<p>This is even harder to describe properly since this seems to be even more haphazard than the undo issues. I do not have many proper examples.</p>
<p>On the screen I have worked with while checking and re-checking some stuff for this post I had a button. I changed the visibility to gone, then to invisible and then to visible. Afterwards the view was still drawn as if it were invisible. Reproducible: Of course not <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The editor also tends to ignore size changes (or to revert them when switching between the the XML and then back to the design tab). But nothing of this is easy to pin down and reproducing these issues is unreliable as well <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> I do not envy the Googlers having to fix these type of arbitrary issues. And I am sorry for not being able to be more specific. But whoever uses the editor will stumble upon the undo and unreliability issues pretty quickly.</p>
<h3>Suggestions for additions</h3>
<p>Currently I have two suggestions for the layout and three for the editor:</p>
<ul>
<li>Add width constraints based on other views</li>
<li><s>Add an aspect-ratio constraint</s></li>
<li>Add Ctrl-Mousewheel scrolling to the layout editor</li>
<li>Allow changes in the blueprint view only</li>
<li>Make the guideline's orientation indicator select the guideline</li>
</ul>
<p>Of course there might be more suggestions in the future when I'm actually going to use <code class="preserve-code-formatting">ConstraintLayout</code> for productive projects. But right now I think those additions would help a lot.</p>
<p>Now let me tell a bit about why I would like to see those items realized.</p>
<h4>Add width and height constraints based on other views</h4>
<p>For some screens I would like to ensure that neighbouring elements use the same width (or height) - but not a fixed width. For example you want buttons to divide up all of the width available. Or two images next to each other.</p>
<p>With <code class="preserve-code-formatting">LinearLayout</code> you would simply set the layout's width to <code class="preserve-code-formatting">match_parent</code> and then use <code class="preserve-code-formatting">layout_width=&quot;0&quot;</code> and <code class="preserve-code-formatting">layout_weight=&quot;1&quot;</code> on its children and they would divide up the available space.</p>
<p>When I first experimented with <code class="preserve-code-formatting">ConstraintLayout</code> I thought, that would be easy. Simply use three buttons next to each other, align each of the right ones to the one left of it and finally the left button to the left edge of the screen and the right one to the right edge of the screen. And then make all of them stretch. But this didn't work as expected:</p>
<figure id="attachment_3482" aria-describedby="caption-attachment-3482" style="width: 500px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected-500x285.png" alt="Three buttons not taking up equal space" width="500" height="285" class="size-medium wp-image-3482" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected-500x285.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected-768x439.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected-700x400.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_not_as_expected.png 993w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3482" class="wp-caption-text">Three buttons not taking up equal space</figcaption></figure>
<p>What you see here is that the first two are as they would be with a width of <code class="preserve-code-formatting">wrap_content</code> and only the last one is actually stretched. In a bug report I filed, a Googler remarked that this works as designed. Stretch doesn't divide up the remaining space between all stretching views. Keep this in mind!</p>
<p>But not all is lost: The team plans to add some constraints that would allow us to do this <em>in the future</em>. Meaning <em>after</em> the first release of <code class="preserve-code-formatting">ConstraintLayout</code>. The bad part is, that we do not have this right away. The good part is, that they have much more plans for this layout and that we can expect it to get better over time.</p>
<h5>Guidelines to the rescue</h5>
<p>But even with the first release not having width constraints, we might be able to achieve this, depending on the specific layout at hand.</p>
<p>For the layout shown above the solution is to use Guildeline objects to divide up the space and then align the buttons to it. Here's what the workaround looks like (click on the image to see its original size):</p>
<figure id="attachment_3485" aria-describedby="caption-attachment-3485" style="width: 500px" class="wp-caption alignnone"><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected-500x285.png" alt="Three buttons now equally spaced" width="500" height="285" class="size-medium wp-image-3485" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected-500x285.png 500w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected-768x438.png 768w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected-700x399.png 700w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/three_buttons_working_as_expected.png 1179w" sizes="auto, (max-width: 500px) 100vw, 500px" /></a><figcaption id="caption-attachment-3485" class="wp-caption-text">Three buttons now equally spaced</figcaption></figure>
<p>And since sometimes code is easier to understand, you can find the code for this layout in <a href="https://gist.github.com/writtmeyer/6553da0c5b2b942e6af7bdee893645b0#file-constraintlayout_three_buttons-xml" title="ConstraintLayout with three buttons taking up equal space">this gist</a>. The gist contains the correctly sized buttons as well as the first attempt without guidelines.</p>
<p><s></p>
<h4>Add an aspect-ratio constraint</h4>
<p></s><br />
<a href="https://plus.google.com/+RomainGuy/posts" title="Google+ page of Romain Guy">Romain Guy</a> pointed out in the comments that the ConstraintLayout indeed has this feature. I'm going to add some more information about how to use it soon. Stay tuned!</p>
<p><s>Even though I never published it, I once made a board game. For things like this it would be nice to have the ability to ensure that this view always has the same height as it's width. And I can also imagine other use cases where elements should use a certain height depending on the device width. Say half the height as the view's width. </p>
<p>You can achieve this with custom views (and in the case of game boards that's the most logical thing to use anyway), but I still guess this addition could make a lot of sense. Especially for <code class="preserve-code-formatting">ImageView </code>objects.</p>
<p>Whatever one might think of Auto Layout, there's a reason Apple provides it there.</s></p>
<h4>Make the guideline's orientation indicator select the guideline</h4>
<p>If you add guidelines they get an indicator at the top (or on the left for horizontal guidelines) which show whether a guideline is positioned at a fixed margin or at a percentage of the total width. Here's the indicator for a percentage:</p>
<figure id="attachment_3487" aria-describedby="caption-attachment-3487" style="width: 123px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/position_indicator_for_guideline.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/position_indicator_for_guideline.png" alt="The position indicator for a guideline" width="123" height="145" class="size-full wp-image-3487" /></a><figcaption id="caption-attachment-3487" class="wp-caption-text">The position indicator for a guideline</figcaption></figure>
<p>It would feel more natural if I could select the guideline by clicking on this indicator. Right now I first have to select the guideline by clicking somewhere on the line itself. Afterwards I can use the indicator to drag the guideline around or to change the type of indicator. Why not directly so?</p>
<h4>Add Ctrl + Mouse Wheel scrolling to the layout editor</h4>
<p>The layout editor can get very crowded - depending on the amount of views, how close they are and how they are constrained. In some cases it would be convenient to quickly zoom into the screen, do some designing, and then quickly zoom out again. It also would be really helpful while  presenting about the editor and the <code class="preserve-code-formatting">ConstraintLayout</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>This is what we're used to when using graphics software. And Android Studio has a setting to allow this way of zooming for text:</p>
<figure id="attachment_3489" aria-describedby="caption-attachment-3489" style="width: 353px" class="wp-caption alignnone"><a href="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/ctrl_mousewheel_zoom.png"><img loading="lazy" decoding="async" src="//www.grokkingandroid.com/wordpress/wp-content/uploads/2016/07/ctrl_mousewheel_zoom.png" alt="Ctrl + Mouse Wheel setting for text in Android Studio" width="353" height="36" class="size-full wp-image-3489" /></a><figcaption id="caption-attachment-3489" class="wp-caption-text">Ctrl + Mouse Wheel setting for text in Android Studio</figcaption></figure>
<p>Thus I would like to see, the zooming to work for the layout editor whenever this setting is checked in Android Studio.</p>
<h4>Allow changes to be made in the blueprint view only</h4>
<p>Currently it's possible to change layout settings in the blueprint view - but also in the preview view. I think the latter should not be possible at all. Restrict designing to the blueprint. If you do so, the preview would be less cluttered - and also might perform better.</p>
<p>The most important reason in my opinion though is, that we are then free to actually use the preview as it should be: A realistic preview. I have already mentioned that the preview is not correct in all cases. And this has to do with the fact that you should be able to drag views around there as well. But if we drop the need for this, we actually can see problems like missing constraints right away.</p>
<h3>What about LinearConstraintLayout and TableConstraintLayout</h3>
<p>I just had a cursory look at both. Thus I do not have an opinion on them. Maybe in some later post. Depends on how they turn out.</p>
<p>One thing is worth mentioning, though: Those two layouts exist, but Google doesn't explain them at all. I think they didn't even mention them during their IO talk. So that's the one thing I <em>can</em> say: Please let us know what you intend to do with these <code class="preserve-code-formatting">ConstraintLayout</code> children and what they should be useful for. I actually have a hard time seeing much use of <code class="preserve-code-formatting">LinearConstraintLayout</code> for example - but hopefully Google proves me wrong.</p>
<h3>Does Anko support ConstraintLayout?</h3>
<p>For those that use Kotlin and like to use <a href="https://github.com/Kotlin/anko" title="Github home of the Anko project">Anko</a> as an alternative to XML, the answer right now is: No! Anko doesn't support <code class="preserve-code-formatting">ConstraintLayout</code>.</p>
<p><a href="https://twitter.com/yanex_ru" title="Yan Zhulanow's twitter account">Yan Zhulanow</a> opened <a href="https://github.com/Kotlin/anko/issues/210">issue #210</a> within the Anko project to add support for <code class="preserve-code-formatting">ConstraintLayout</code> to Anko. Right now, no further comments have been added. But most likely this will be fixed soon.</p>
<h3>To sum things up</h3>
<p>The new layout and the new layout editor both show promise. They are currently in alpha (the layout) or preview (the editor), so we can expect to see many - if not all - of the problems ironed out until the final release of both of them.</p>
<p>It's definitely worth getting yourself accustomed with the new layout. I'm quite confident that it is the future. </p>
<p>Having said that, I <em>currently</em> don't use the <code class="preserve-code-formatting">ConstraintLayout</code> for real projects. But I expect to be able to do so pretty soon.</p>
<p>Please note that everything I have written here is based on what I <em>currently</em> think about the <code class="preserve-code-formatting">ConstraintLayout</code> and the design editor. There have been lots of improvements during the last iterations of both the <code class="preserve-code-formatting">ConstraintLayout</code> and the editor and I expect this to go on. </p>
<p>Also keep in mind, that we are only starting to understand the possibilities of <code class="preserve-code-formatting">ConstraintLayout</code>! The more we use it the more we will know how to do stuff. I'm actually quite excited about it - despite some of the problems the alpha still has. </p>
<p>I very much appreciate what the Googlers are doing there! Keep up the good work - and thanks!</p>
<div class="box">
Let me finally thank those nice folks of the <a href="http://www.meetup.com/dutch-aug/" title="Meetup page of the Dutch Android User Group">Dutch Android User Group</a>. I had the opportunity to speak about <code class="preserve-code-formatting">ConstraintLayout</code> at their <a href="http://www.meetup.com/dutch-aug/events/231331235/">Google IO Extended Extended</a>. Many of the thoughts in here are the result of my preparations for the talk and feedback about the demo afterwards. </p>
<p>If you're not doing so already, I thoroughly recommend to go to the meetups and devfests of your local Google Developer Group. Here's a <a href="https://developers.google.com/groups/directory/" title="Directory of all GDGs worldwide">map of Google Developer Groups worldwide</a>, if you're not sure where the next one is. </p>
<p>BTW: My local chapter is <a href="http://www.meetup.com/Google-Developer-Group-Dusseldorf/" title="Meetup page of the GDG Düsseldorf">Düsseldorf</a>. We are nice folks, enjoy pizza and are always on the lookout for good talks. <a href="https://plus.google.com/events/gallery/cl7vl58i58ugnugnbfo8un439n4">See these shots of a typical meetup</a>.
</div>
<div class="copy"><em>In the project for this post I made use of the image <a href="https://flic.kr/p/CPxoSy">Rolls Royce</a> by Wendelin Jacober and <a href="https://flic.kr/p/ofTNQ3">Hygiene is important</a> by Wyncliffe. Both images are released in the public domain.</em></div>
<p>The post <a href="https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/">Some Thoughts on Android&#8217;s new ConstraintLayout and Android Studio&#8217;s new Design Editor</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/thoughts-on-constraintlayout-and-design-editor/feed/</wfw:commentRss>
			<slash:comments>12</slash:comments>
		
		
			</item>
		<item>
		<title>RxJava&#8217;s Side Effect Methods</title>
		<link>https://www.grokkingandroid.com/rxjavas-side-effect-methods/</link>
					<comments>https://www.grokkingandroid.com/rxjavas-side-effect-methods/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 10 Nov 2015 08:40:16 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[doOnCompleted]]></category>
		<category><![CDATA[doOnEach]]></category>
		<category><![CDATA[doOnError]]></category>
		<category><![CDATA[doOnNext]]></category>
		<category><![CDATA[doOnSubscribe]]></category>
		<category><![CDATA[RxJava]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3297</guid>

					<description><![CDATA[<p>RxJava's Observable class has plenty of methods that can be used to transform the stream of emitted items to the kind of data that you need. Those methods are at the very core of RxJava and form a big part of it's attraction. But there are other methods, that do not change the stream of [...]&#160;&#160;<a href="https://www.grokkingandroid.com/rxjavas-side-effect-methods/">Continue Reading&#160;&#160;"RxJava&#8217;s Side Effect Methods"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/rxjavas-side-effect-methods/">RxJava&#8217;s Side Effect Methods</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>RxJava's Observable class has plenty of methods that can be used to transform the stream of emitted items to the kind of data that you need. Those methods are at the very core of RxJava and form a big part of it's attraction. </p>
<p>But there are other methods, that do not change the stream of items in any way - I call those methods side effect methods.</p>
<h3>What do I mean by side effect methods?</h3>
<p>Side effect methods do not affect your stream in itself. Instead they are invoked when certain events occur to allow you to react to those events. </p>
<p>For example: if you're interested in doing something outside of your <code class="preserve-code-formatting">Subscriber</code>'s callbacks whenever some error occurs, you would use the <code class="preserve-code-formatting">doOnError()</code> method and pass to it the <a href="http://www.lambdafaq.org/what-is-a-functional-interface/" title="Good explanation of what Functional Interfaces are">functional interface</a> to be used whenever an error occurs:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
someObservable
      .doOnError(new Action1() {
         @Override
         public void call(Throwable t) {
            // use this callback to clean up resources,
            // log the event or or report the 
            // problem to the user
         }
      })
      //...</code></pre>
</div>
<p>The most important part is the <code class="preserve-code-formatting">call()</code> method. The code of this method will be executed before the <code class="preserve-code-formatting">Subscriber</code>'s <code class="preserve-code-formatting">onError()</code> method is called. </p>
<p>In addition to exceptions RxJava offers many more events to which you can react:</p>
<table>
<caption>Events and their corresponding side effect operations</caption>
<tr>
<th>Method</th>
<th>Functional Interface</th>
<th>Event</th>
</tr>
<tr>
<td>doOnSubscribe()</td>
<td>Action0</td>
<td>A subscriber subscribes to the Observable</td>
</tr>
<tr>
<td>doOnUnsubscribe()</td>
<td>Action0</td>
<td>A subscriber unsubscribes from the subscription</td>
</tr>
<tr>
<td>doOnNext()</td>
<td>Action1&lt;T&gt;</td>
<td>The next item is emitted</td>
</tr>
<tr>
<td>doOnCompleted()</td>
<td>Action0</td>
<td>The Observable will emit no more items</td>
</tr>
<tr>
<td>doOnError()</td>
<td>Action1&lt;T&gt;</td>
<td>An error occurred</td>
</tr>
<tr>
<td>doOnTerminate()</td>
<td>Action0</td>
<td>Either an error occurred or the Observable will emit no more items - will be called <em>before</em> the termination methods</td>
</tr>
<tr>
<td>finallyDo()</td>
<td>Action0</td>
<td>Either an error occurred or the Observable will emit no more items - will be called <em>after</em> the termination methods</td>
</tr>
<tr>
<td>doOnEach()</td>
<td>Action1&lt;Notification&lt;T&gt;&gt;</td>
<td>Either an item was emitted, the Observable completes or an error occurred. The Notification object contains information about the type of event</td>
</tr>
<tr>
<td>doOnRequest()</td>
<td>Action1&lt;Long&gt;</td>
<td>A downstream operator requests to emit more items</td>
</tr>
</table>
<p>The &lt;T&gt; refers either to the type of the item emitted or, in the case of the <code class="preserve-code-formatting">onError()</code> method, the type of the Throwable thrown.</p>
<p>The functional interfaces are all of type <a href="http://reactivex.io/RxJava/javadoc/rx/functions/Action0.html" title="documentation of RxJava's functional interface Action0">Action0</a> or <a href="http://reactivex.io/RxJava/javadoc/rx/functions/Action1.html" title="documentation of RxJava's functional interface Action1">Action1</a>. This means that the single methods of these interfaces do not return anything and take either zero arguments or one argument, depending on the specific event. </p>
<p>Since those methods do not return anything, they cannot be used to change the emitted items and thus do not change the stream of items in any way. Instead these methods are intended to cause side effects like writing something on disk, cleaning up state or anything else that manipulates the state of the system itself instead of the stream of events.</p>
<p><strong>Note:</strong> The side effect methods themselves (doOnNext(), doOnCompleted() and so on) <em>do</em> return an Observable. That's to keep the interface fluent. But the returned Observable is of the same type and emits the same items as the source Observable.</p>
<h3>What are they useful for?</h3>
<p>Now since they do not change the stream of items there must be other uses for them. I present here three examples of what you can achieve using these methods:</p>
<ul>
<li>Use <code class="preserve-code-formatting">doOnNext()</code> for debugging</li>
<li>Use <code class="preserve-code-formatting">doOnError()</code> within <code class="preserve-code-formatting">flatMap()</code> for error handling</li>
<li>Use <code class="preserve-code-formatting">doOnNext()</code> to save/cache network results</li>
</ul>
<p>So let's see these examples in detail.</p>
<h4>Use doOnNext() for debugging</h4>
<p>With RxJava you sometimes wonder why your <code class="preserve-code-formatting">Observable</code> isn't working as expected. Especially when you are just starting out. Since you use a fluent API to transform some source into something that you want to subscribe to, you only see what you get at the end of this transformation pipeline.</p>
<p>When I was learning about RxJava I had some initial experience with Java's Streams. Basically you have the same problem there. You have a fluid API to move from one Stream of some type to another Stream of another type. But what if it doesn't work as expected? </p>
<p>With Java 8 Streams you have the <code class="preserve-code-formatting">peek()</code> method. So when starting out with RxJava I wondered if something comparable is available. Well, there is. Actually, RxJava offers much more!</p>
<p>You can use the <code class="preserve-code-formatting">doOnNext()</code> method anywhere in your processing pipeline to see what is happening and what the intermediary result is.</p>
<p>Here's an example of this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
Observable someObservable = Observable
            .from(Arrays.asList(new Integer[]{2, 3, 5, 7, 11}))
            .doOnNext(System.out::println)
            .filter(prime -&gt; prime % 2 != 0)
            .doOnNext(System.out::println)
            .count()
            .doOnNext(System.out::println)
            .map(number -&gt; String.format("Contains %d elements", number));

Subscription subscription = o.subscribe(
            System.out::println,
            System.out::println,
            () -&gt; System.out.println("Completed!"));</code></pre>
</div>
<p>And here is the output of that code:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
2
3
3
5
5
7
7
11
11
4
Contains 4 elements
Completed!</code></pre>
</div>
<p>That way you can glean valuable information about what is going on when your Observable doesn't behave as you expected. </p>
<p>The <code class="preserve-code-formatting">doOnError()</code> and <code class="preserve-code-formatting">doOnCompleted()</code> methods can also be useful for debugging the state of your pipeline. </p>
<p><strong>Note:</strong> If you're using RxJava while developing for Android please have a look at the <a href="https://github.com/android10/frodo" title="Github page of the library Frodo">Frodo</a> and Fernando Ceja's post explaining about the <a href="http://fernandocejas.com/2015/11/05/debugging-rxjava-on-android/" title="Fernando Ceja's post about Frodo">motivation for and usage of Frodo</a>. With Frodo you can use annotations to debug your <code class="preserve-code-formatting">Observables</code> and <code class="preserve-code-formatting">Subscribers</code>.</p>
<p>The shown way of using <code class="preserve-code-formatting">doOnNext()</code> and <code class="preserve-code-formatting">doOnError()</code> does not change much of the system state - apart from bloating your log and slowing everything down. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>But there are other uses for these operators. And in those cases you use those methods to actually change the state of your system. Let’s have a look at them.</p>
<h4>Use doOnError() within flatMap()</h4>
<p>Say you're using <a href="http://square.github.io/retrofit/" title="Square's Retrofit page">Retrofit</a> to access some resource over the network. Since Retrofit supports observables, you can easily use those calls within your processing chain using <code class="preserve-code-formatting">flatMap()</code>.</p>
<p>Alas, network related calls can go wrong in many ways - especially on mobiles. In this case you might not want the <code class="preserve-code-formatting">Observable</code> to stop working, which it would if you were to rely on your subscriber's <code class="preserve-code-formatting">onError()</code> callback alone.</p>
<p>But keep in mind that you have an Observable within your <code class="preserve-code-formatting">flatMap()</code> method. Thus you could use the <code class="preserve-code-formatting">doOnError()</code> method to change the UI in some way, yet still have a working Observable stream for future events. </p>
<p>So what this looks like is this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
flatMap(id -&gt; service.getPost()
       .doOnError(t -&gt; {
          // report problem to UI
       })
       .onErrorResumeNext(Observable.empty())
)</code></pre>
</div>
<p>This method is especially useful if you query your remote resource as a result of potentially recurring UI events.</p>
<h4>Use doOnNext() to save/cache network results</h4>
<p>If at some point in your chain you make network calls, you could use <code class="preserve-code-formatting">doOnNext()</code> to store the incoming results to your local database or put them in some cache.</p>
<p>It would be as simple as the following lines:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
// getOrderById is getting a fresh order 
// from the net and returns an observable of orders
// Observable&lt;Order&gt; getOrderById(long id) {...}

Observable.from(aListWithIds)
         .flatMap(id -&gt; getOrderById(id)
                              .doOnNext(order -&gt; cacheOrder(order))
         // carry on with more processing</code></pre>
</div>
<p>See this pattern applied in more detail in Daniel Lew's excellent blog post about <a href="http://blog.danlew.net/2015/06/22/loading-data-from-multiple-sources-with-rxjava/" title="Dan Lew's post about how to access multiple sources with RxJava">accessing multiple sources</a>.</p>
<h3>Wrap up</h3>
<p>As you've seen, you can use the side effect methods of RxJava in multiple ways. Even though they do not change the stream of emitted items, they change the state of your overall system. This can be something as simple as logging the current items of your <code class="preserve-code-formatting">Observable</code> at a certain point within your processing pipeline, up to writing objects to your database as a result of a network call.</p>
<p>In my next post I am going to show you how to use RxJava's hooks to get further insights. Stay tuned!</p>
<p>The post <a href="https://www.grokkingandroid.com/rxjavas-side-effect-methods/">RxJava&#8217;s Side Effect Methods</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/rxjavas-side-effect-methods/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Why use Observable.create() and not just inherit from Observable?</title>
		<link>https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/</link>
					<comments>https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/#respond</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Fri, 09 Oct 2015 05:00:40 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[create()]]></category>
		<category><![CDATA[Observable]]></category>
		<category><![CDATA[RxJava]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3281</guid>

					<description><![CDATA[<p>When starting to use RxJava you have to create Observables. They are at the very core of RxJava. But how to do so? A look at the Observable class might make you dizzy. Looking at the source even more so. Not only does this beast consist of nearly 10.000 lines (though, 7600 lines of that [...]&#160;&#160;<a href="https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/">Continue Reading&#160;&#160;"Why use Observable.create() and not just inherit from Observable?"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/">Why use Observable.create() and not just inherit from Observable?</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When starting to use <a href="https://github.com/ReactiveX/RxJava/wiki" title="Wiki of RXJava's github page">RxJava</a> you have to create Observables. They are at the very core of RxJava. But how to do so?</p>
<p>A look at the <a href="http://reactivex.io/RxJava/javadoc/rx/Observable.html" title="Documentation of RxJava's Observable class">Observable</a> class might make you dizzy. Looking at the source even more so. Not only does this beast consist of nearly 10.000 lines (though, 7600 lines of that are comments) but it also consists of a bunch of final methods. Actually only final methods! 330 of them! But you <em>can</em> inherit from <code class="preserve-code-formatting">Observable</code>. Odd, very odd!</p>
<p>Next you might think: Ah never mind, let me just inherit from <code class="preserve-code-formatting">Observable</code> and see how far I get.</p>
<p>But should you bother to look at the documentation of the constructor, you see this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
<em>Note:</em> Use create(OnSubscribe) to create an Observable, instead of this constructor,
unless you specifically have a need for inheritance.</code></pre>
</div>
<p>Okay, since you are eager to know what this is all about: you have a short look at the documentation of <code class="preserve-code-formatting">onCreate()</code>:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
Returns an Observable that will execute the specified function when a Subscriber subscribes to
it.
...
Write the function you pass to create so that it behaves as an Observable: It should invoke the
Subscriber's onNext, onError, and onCompleted methods appropriately.
...
A well-formed Observable must invoke either the Subscriber's onCompleted method exactly once or
its onError method exactly once.</code></pre>
</div>
<p>Hm... Maybe a look at this method’s code might help?</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public final static  Observable create(OnSubscribe f) {
   return new Observable(hook.onCreate(f));
}</code></pre>
</div>
<p><strong>What?</strong> It's just passing this stuff to the constructor anyway? So what's it with this warning?</p>
<p>Well, first: Why would you want to inherit <code class="preserve-code-formatting">Observable</code> in the first place? All methods of it are final. You basically cannot add much functionality to <code class="preserve-code-formatting">Observable</code> <em>by inheritance</em> because of this. It's better to stick to the RxJava way to do things: And that is by chaining API calls of its fluent API.</p>
<p>Another thing is, that it's not as explicit. Using the <code class="preserve-code-formatting">create()</code> method you directly see what the created <code class="preserve-code-formatting">Observable</code> is up to.</p>
<p>Furthermore: If you look more closely at the source snippet, you will notice this tiny little <code class="preserve-code-formatting">hook.onCreate()</code> call. That's actually quite important. Because RxJava allows you to supply hooks that wrap certain method calls and allow you to substitute certain aspects of how RxJava behaves.</p>
<p>I for one use this hook in debug mode to log which thread my observables get created on and on what threads operators are lifted. In server environments you might want to add monitoring logic to your hooks. By using the constructor, you bypass this and rob yourself of the possibility to do so easily.</p>
<p>Having said all this: It's not forbidden to inherit from Observable. As with all rules, there are situations where they do not apply and where inheritance <em>does</em> make sense. The <a href="http://reactivex.io/RxJava/javadoc/rx/subjects/Subject.html" title="Documentation of RxJava's Subject class">Subject</a> class for example does inherit from Observable. Just be careful and try to think twice when doing so&nbsp; <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/">Why use Observable.create() and not just inherit from Observable?</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/why-use-observable-create-and-not-just-inherit-from-observable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Selecting Items of a RecyclerView using StateListDrawables</title>
		<link>https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/</link>
					<comments>https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Fri, 22 Aug 2014 08:16:21 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Adapter]]></category>
		<category><![CDATA[Contextual ActionBar]]></category>
		<category><![CDATA[RecyclerView]]></category>
		<category><![CDATA[StateListDrawable]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=3038</guid>

					<description><![CDATA[<p>Last week, after I published my introduction to RecyclerView Paul Betts asked on Twitter whether ItemDecorators are useful for displaying the selection state of items. Well, I think using them for selection is not the right way to go. Instead, I think that you should stick with StateListDrawables and the activated state. The use case [...]&#160;&#160;<a href="https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/">Continue Reading&#160;&#160;"Selecting Items of a RecyclerView using StateListDrawables"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/">Selecting Items of a RecyclerView using StateListDrawables</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Last week, after I published my introduction to <code class="preserve-code-formatting">RecyclerView</code> <a href="https://twitter.com/paulcbetts" title="Twitter profile of Paul Betts">Paul Betts</a> asked on Twitter whether <code class="preserve-code-formatting">ItemDecorators</code> are useful for displaying the <a href="https://twitter.com/paulcbetts/status/499904899531145216" title="Paul's Tweet with his question on what to use to display the selected state">selection state of items</a>.</p>
<p>Well, I think using them for selection is not the right way to go. Instead, I think that you should stick with <a href="http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList" title="Documentation of Android's StateListDrawables">StateListDrawables</a> and the activated state.</p>
<h3>The use case of the sample</h3>
<p>In this sample the user can select multiple items that are shown in purple. The first item gets selected using a long click. Any subsequent click will select or deselect items. Users can also deselect items, that were previously selected, with a single click. The user can then use a bulk delete operation on all selected items. The user should be able to see the number of currently selected items.</p>
<p>Obviously that sounds a lot like a contextual action bar (CAB), which is what I used. BTW: As you can see in the screenshot, the CAB doesn't look like I expected it to look. It should use my <code class="preserve-code-formatting">android:colorPrimaryDark</code> for the contextual app bar (Material lingo). But either the <a href="https://developer.android.com/preview/material/theme.html" title="Guide for using Material design themes ">theming guide for material design</a> is not correct, or maybe it's the current L preview, or - more likely - it's my code. Any takers? Please let me know, if you know what's wrong here. Thanks!</p>
<p>Here's a screenshot of the final result. You can also find a video near the end of this post. </p>
<figure id="attachment_3103" aria-describedby="caption-attachment-3103" style="width: 180px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_with_cab_and_selection1.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_with_cab_and_selection1-180x300.png" alt="RecyclerView with Contextual ActionBar and selected items" width="180" height="300" class="size-medium wp-image-3103" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_with_cab_and_selection1-180x300.png 180w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_with_cab_and_selection1.png 480w" sizes="auto, (max-width: 180px) 100vw, 180px" /></a><figcaption id="caption-attachment-3103" class="wp-caption-text">RecyclerView with Contextual ActionBar and selected items</figcaption></figure>
<h3>Overview</h3>
<p>The solution that I suggest is Adapter-based. As you might recall from my <a href="http://www.grokkingandroid.com/first-glance-androids-recyclerview/" title="A First Glance at Android’s RecyclerView and its Inner Classes">last post</a>, <code class="preserve-code-formatting">RecyclerView</code> doesn't care about the visual representation of individual items. Thus I quickly ruled out to subclass <code class="preserve-code-formatting">RecyclerView</code>. </p>
<p><code class="preserve-code-formatting">RecyclerView</code> doesn't itself need to know about the set of items nor about the state these items are in. In this way my proposed solution differs from the way you did selections with <a href="http://developer.android.com/reference/android/widget/ListView.html" title="Android documentation of the ListView class">ListView</a> or <a href="http://developer.android.com/reference/android/widget/GridView.html" title="Documentation of Android's GridView class">GridView</a> in the past. There you checked items directly using the  <a href="http://developer.android.com/reference/android/widget/AbsListView.html#setItemChecked%28int,%20boolean%29" title="Documentation of AbsListView's setItemChecked() method">setItemChecked()</a> method and you set the kind of selection mode with <a href="http://www.grokkingandroid.com/first-glance-androids-recyclerview/" title="Documentation of AbsListView's setChoiceMode() method">setChoiceMode()</a>.</p>
<p>With <code class="preserve-code-formatting">RecyclerView</code> any information about the data set belongs to your <code class="preserve-code-formatting">RecyclerView.Adapter</code> subclass. Thus anything required to show the selection state of items should also be in your <code class="preserve-code-formatting">RecyclerView.Adapter</code> subclass.</p>
<p>The adapter not only stores information about the state of each item, but it also creates the views for each items. That's why I use the adapter for setting the activated state.</p>
<h3>Methods for setting the selected state</h3>
<p>Based on this use case, I chose to add the following methods to my <code class="preserve-code-formatting">RecyclerView.Adapter</code> subclass:</p>
<ul>
<li><code class="preserve-code-formatting">void toggleSelection(int pos)</code></li>
<li><code class="preserve-code-formatting">void clearSelections()</code></li>
<li><code class="preserve-code-formatting">int getSelectedItemCount()</code></li>
<li><code class="preserve-code-formatting">List&amp;lt;Integer&amp;gt; getSelectedItems()</code></li>
</ul>
<p>With <code class="preserve-code-formatting">toggleSelection()</code> an item changes its selection state. If it was previously selected it gets deselected, and vice versa.</p>
<p>You can always clear all selections with <code class="preserve-code-formatting">clearSelections()</code>. You shouldn't forget to do that when you finish the action mode.</p>
<p>The other methods get the number of currently selected items and all positions of the currently selected items.</p>
<h3>Necessary changes to the adapter</h3>
<p>Here's the relevant part of my Adapter:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public class RecyclerViewDemoAdapter
        extends RecyclerView.Adapter
                &lt;RecyclerViewDemoAdapter.ListItemViewHolder&gt; {

   // ...
   private SparseBooleanArray selectedItems;
   
   // ...

   public void toggleSelection(int pos) {
      if (selectedItems.get(pos, false)) {
         selectedItems.delete(pos);
      }
      else {
         selectedItems.put(pos, true);
      }
      notifyItemChanged(pos);
   }
   
   public void clearSelections() {
      selectedItems.clear();
      notifyDataSetChanged();
   }
   
   public int getSelectedItemCount() {
      return selectedItems.size();
   }
   
   public List&lt;Integer&gt; getSelectedItems() {
      List&lt;Integer&gt; items = 
            new ArrayList&lt;Integer&gt;(selectedItems.size());
      for (int i = 0; i &lt; selectedItems.size(); i++) {
         items.add(selectedItems.keyAt(i));
      }
      return items;
   }

   // ...

}</code></pre>
</div>
<p>Notice how I used <code class="preserve-code-formatting">notifyDataSetChanged()</code> and <code class="preserve-code-formatting">notifyItemChanged()</code>. That's necessary because I do not have access to the <code class="preserve-code-formatting">View</code> object itself and thus cannot set the activated state directly. Instead I have to tell Android to ask the Adapter for a new <code class="preserve-code-formatting">ViewHolder</code> binding.</p>
<h3>How to use those methods from within the Activity</h3>
<p>If you have used <code class="preserve-code-formatting">ListViews</code> with the Contextual ActionBar in the past, you know that for selecting multiple items you had to set the choice mode to <code class="preserve-code-formatting">CHOICE_MODE_MULTIPLE_MODAL</code> and implement the <a href="http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html" title="Documentation of Android's MultiChoiceModeListener interface">AbsListview.MultiChoiceModeListener</a> interface to achieve the desired result. See this <a href="http://developer.android.com/guide/topics/ui/menus.html#CAB" title="Explanation of how to use the Contextual ActionBar">guide on Android's developer site</a> for more details. Now since <code class="preserve-code-formatting">RecyclerView</code> doesn't offer this interface (and rightly so), you have to find a way around this.</p>
<p>My solution is to use the <code class="preserve-code-formatting">GestureDetector</code> to detect long presses. You can find this code at the end of the Activity. In the long-press callback, I create the actionmode, detect which view was pressed and call <code class="preserve-code-formatting">toggleSelection()</code> on the adapter.</p>
<div class="sourcecode">
<pre class="language-java line-numbers" data-line="15,18"><code class="language-java line-numbers">
public void onLongPress(MotionEvent e) {
   View view = 
      recyclerView.findChildViewUnder(e.getX(), e.getY());
   if (actionMode != null) {
      return;
   }
   actionMode = 
      startActionMode(RecyclerViewDemoActivity.this);
   int idx = recyclerView.getChildPosition(view);
   myToggleSelection(idx);
   super.onLongPress(e);
}

private void myToggleSelection(int idx) {
   adapter.toggleSelection(idx);
   String title = getString(
         R.string.selected_count, 
         adapter.getSelectedItemCount());
   actionMode.setTitle(title);
}</code></pre>
</div>
<p>For the actionmode to work, the activity has to implement the <a href="http://developer.android.com/reference/android/view/ActionMode.Callback.html" title="Documentation of Android's ActionMode.Callback interface">ActionMode.Callback</a> interface. I won't go into this. It's described in detail in the <a href="http://developer.android.com/guide/topics/ui/menus.html#CAB" title="Guide for using the Contextual ActionBar in Android">official menu guide on the Android site</a>.</p>
<p>To understand of how selections work only two of this interface's methods are interesting:</p>
<ul>
<li><code class="preserve-code-formatting">onActionItemClicked()</code>
<p>Android calls this method when the user presses the delete icon. In this method I get the list of selected items from the adapter and call the <code class="preserve-code-formatting">removeData()</code> method of the adapter for each item - so that Android can smoothly animate them - as shown in the previous post. And, of course, I have to finish the action mode afterwards.</p>
</li>
<li><code class="preserve-code-formatting">onDestroyActionMode()</code>
<p>Android calls this method when it's leaving actionmode prior to showing the normal ActionBar (app bar) again. This happens either when the user selects the check mark or when he/she selects the delete icon.</p>
</li>
</ul>
<p>Here's the code for these two methods:</p>
<div class="sourcecode">
<pre class="language-java line-numbers" data-line="8,12,24"><code class="language-java line-numbers">
@Override
public boolean onActionItemClicked(
         ActionMode actionMode, 
         MenuItem menuItem) {
   switch (menuItem.getItemId()) {
      case R.id.menu_delete:
         List&lt;Integer&gt; selectedItemPositions = 
               adapter.getSelectedItems();
         for (int i = selectedItemPositions.size() - 1; 
               i &gt;= 0; 
               i--) {
            adapter.removeData(selectedItemPositions.get(i));
         }
         actionMode.finish();
         return true;
      default:
         return false;
   }
}

@Override
public void onDestroyActionMode(ActionMode actionMode) {
   this.actionMode = null;
   adapter.clearSelections();
}</code></pre>
</div>
<h3>The StateListDrawable XML file</h3>
<p>So far I have shown you how to select items and set the activated state. To finally highlight those items I use <code class="preserve-code-formatting">StateListDrawables</code>. </p>
<p>A <code class="preserve-code-formatting">StateListDrawable</code> is a drawable that changes its content based on the state of the view. You can define those in XML files. The first matching entry for a given state determines which drawable Android uses. Since I only care about the activated state the XML file is actually very simple:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers" data-line="4,5"><code class="language-markup line-numbers">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;selector xmlns:android=
      &quot;http://schemas.android.com/apk/res/android&quot;&gt;
   &lt;item android:state_activated=&quot;true&quot; 
         android:drawable=&quot;@color/primary_dark&quot; /&gt;
   &lt;item android:drawable=&quot;@android:color/transparent&quot; /&gt;
&lt;/selector&gt;</code></pre>
</div>
<p>And of course you have to use this <code class="preserve-code-formatting">StateListDrawable</code> somewhere. I use it as the background for each item:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers" data-line="5"><code class="language-markup line-numbers">
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/container_list_item&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@drawable/statelist_item_background&quot;&gt;
    &lt;include layout=&quot;@layout/common_item_layout&quot; /&gt;
&lt;/RelativeLayout&gt;</code></pre>
</div>
<p>The following video shows the result of this post's changes:</p>
<div style="width: 480px;" class="wp-video"><video class="wp-video-shortcode" id="video-3038-1" width="480" height="800" preload="metadata" controls="controls"><source type="video/mp4" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_selection_video.mp4?_=1" /><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_selection_video.mp4">https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_selection_video.mp4</a></video></div>
<p class="caption short">A short video showing the Contextual ActionBar and the selection of items</p>
<h3>Sample project</h3>
<p>You can <a href="https://github.com/writtmeyer/recyclerviewdemo" title="RecyclerView Demo project on github">download the sample</a> from my github page. I have tagged the revision of last week's post with "simpleSample" while the revision for this week uses the tag "selectionSample". </p>
<p>Feel free to submit pull requests if you have suggestions on how to improve the code.</p>
<h3>And that's it for today</h3>
<p>This was a short example of how to make use of the <code class="preserve-code-formatting">RecyclerView.Adapter</code> and how to benefit from those abstractions. I guess I won't go into much more detail about the adapter in future posts. But I recommend that you take a look at Gabriele Mariotti's great example of <a href="https://gist.github.com/gabrielemariotti/4c189fb1124df4556058" title="Gist by Gabriele Mariotti showing an RecyclerView.Adapter subclass for sectioned lists">how to use an RecyclerView.Adapter with sectioned lists</a>.</p>
<p>I hope this post helps you in your work with <code class="preserve-code-formatting">RecyclerView.Adapters</code>. Selection is just one of the many things an adapter is useful for. If you have a look at Gabriele's gist, you can see how to use your adapter to support different view types. Just keep in mind the separation of concerns and don't mix responsibilities.</p>
<p>The post <a href="https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/">Selecting Items of a RecyclerView using StateListDrawables</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/statelistdrawables-for-recyclerview-selection/feed/</wfw:commentRss>
			<slash:comments>20</slash:comments>
		
		<enclosure url="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_selection_video.mp4" length="343792" type="video/mp4" />

			</item>
		<item>
		<title>A First Glance at Android&#8217;s RecyclerView</title>
		<link>https://www.grokkingandroid.com/first-glance-androids-recyclerview/</link>
					<comments>https://www.grokkingandroid.com/first-glance-androids-recyclerview/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 14 Aug 2014 09:59:14 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Adapter]]></category>
		<category><![CDATA[Android L]]></category>
		<category><![CDATA[ItemAnimator]]></category>
		<category><![CDATA[ItemDecoration]]></category>
		<category><![CDATA[L Developer Preview]]></category>
		<category><![CDATA[LayoutManager]]></category>
		<category><![CDATA[OnItemTouchListenerter]]></category>
		<category><![CDATA[RecyclerView]]></category>
		<category><![CDATA[ViewHolder]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2980</guid>

					<description><![CDATA[<p>At this year's Google I/O, Google released a preview to the upcoming Android version. The so called L Developer Preview. This is a very big improvement over previous releases and I really love that Google is doing this. I think we all benefit by this decision. As developers and as consumers alike! Part of this [...]&#160;&#160;<a href="https://www.grokkingandroid.com/first-glance-androids-recyclerview/">Continue Reading&#160;&#160;"A First Glance at Android&#8217;s RecyclerView"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/first-glance-androids-recyclerview/">A First Glance at Android&#8217;s RecyclerView</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>At this year's Google I/O, Google released a preview to the upcoming Android version. The so called <a href="http://developer.android.com/preview/index.html" title="The homepage of the L preview release">L Developer Preview</a>. This is a very big improvement over previous releases and I really love that Google is doing this. I think we all benefit by this decision. As developers and as consumers alike!</p>
<p>Part of this preview are two new views: <code class="preserve-code-formatting">RecyclerView</code> and <code class="preserve-code-formatting">CardView</code>. This post gives you an introduction to the <code class="preserve-code-formatting">RecyclerView</code>, it's many internal classes and interfaces, how they interact and how you can use them.</p>
<p>Let me start with the good news: <strong>RecyclerView is part of the support library</strong>. So you can use it right now. Ok: You can use it as soon as the final support lib accompanying the L release gets released. So better to familiarize yourself with it right away <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Sample project</h3>
<p>The screenshots and the video at the end of the post show the sample project for this post in action. You can find the <a href="https://github.com/writtmeyer/recyclerviewdemo" title="Project page for my RecyclerView sample on github">source of this sample at github</a>. Keep in mind that the RecyclerView API is not yet finalized. Google might still change things that could break the sample when they release the final version of Android L.</p>
<h3>What's with this odd name? Why RecyclerView?</h3>
<p>This is how Google describes <code class="preserve-code-formatting">RecyclerView</code> in the API documentation of the L preview release:</p>
<blockquote><p>A flexible view for providing a limited window into a large data set.</p></blockquote>
<p>So <code class="preserve-code-formatting">RecyclerView</code> is the appropriate view to use when you have multiple items of the same type and it's very likely that your user's device cannot present all of those items at once. Possible examples are contacts, customers, audio files and so on. The user has to scroll up and down to see more items and that's when the <strong>recycling and reuse comes into play</strong>. As soon as a user scrolls a currently visible item out of view, this item's view can be recycled and reused whenever a new item comes into view.</p>
<p>The following screenshots of the sample app illustrate this. On the left is the sample app after the initial start. When you scroll the view up, some views become eligible for recycling. The red area on the right screenshot, for example,  highlights two invisible views. The recycler can now put these views into a list of candidates to be reused should a new view be necessary.</p>
<figure id="attachment_3055" aria-describedby="caption-attachment-3055" style="width: 300px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recycling_of_views.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recycling_of_views-300x227.png" alt="These two screens show what recycling means. On the right two views are eligible for reuse" width="300" height="227" class="size-medium wp-image-3055" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recycling_of_views-300x227.png 300w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recycling_of_views-1024x777.png 1024w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recycling_of_views.png 1248w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-3055" class="wp-caption-text">These two screens show what recycling means. On the right two views are eligible for reuse</figcaption></figure>
<p>Recycling of views is a very useful approach. It saves CPU resources in that you do not have to inflate new views all the time and it saves memory in that it doesn't keep plenty of invisible views around.</p>
<p>Now, you might say: That's nothing new. And you're right! We had that with <code class="preserve-code-formatting">ListView</code> for a very long time. The concept of recycling views <em>itself</em> it not new. But while you previously had a <code class="preserve-code-formatting">ListView</code> where the appearance, recycling and everything was tightly coupled, Google now follows a much better, a much more flexible approach with the new <code class="preserve-code-formatting">RecyclerView</code>. I really like the approach Google has taken here!</p>
<h3>RecyclerView doesn't care about visuals</h3>
<p>Here's the thing: While with <code class="preserve-code-formatting">Listview</code> we had tight coupling, Google now uses an approach where the <code class="preserve-code-formatting">RecyclerView</code> itself doesn't care about visuals at all. It doesn't care about placing the elements at the right place, it doesn't care about separating any items and not about the look of each individual item either. To exaggerate a bit: All <code class="preserve-code-formatting">RecyclerView</code> does, is recycle stuff. Hence the name.</p>
<p>Anything that has to do with layout, drawing and so on, that is <strong>anything that has to do with how your data set is presented, is delegated to pluggable classes.</strong> That makes the new <code class="preserve-code-formatting">RecyclerView</code> API extremely flexible. You want another layout? Plug in another <code class="preserve-code-formatting">LayoutManager</code>. You want different animations? Plug in an <code class="preserve-code-formatting">ItemAnimator</code>. And so on.</p>
<p>Here's the list of the most important classes that <code class="preserve-code-formatting">RecyclerView</code> makes use of to present the data. All these classes are inner classes of the RecyclerView:</p>
<table>
<caption>The most important classes of the RecyclerView API</caption>
<tr>
<th>Class</th>
<th>Usage</th>
</tr>
<tr>
<td>Adapter</td>
<td>Wraps the data set and creates views for individual items</td>
</tr>
<tr>
<td>ViewHolder</td>
<td>Holds all sub views that depend on the current item's data</td>
</tr>
<tr>
<td>LayoutManager</td>
<td>Places items within the available area</td>
</tr>
<tr>
<td>ItemDecoration</td>
<td>Draws decorations around or on top of each item's view</td>
</tr>
<tr>
<td>ItemAnimator</td>
<td>Animates items when they are added, removed or reordered</td>
</tr>
</table>
<p>In the next paragraphs I will briefly describe what each class or interface is about and how <code class="preserve-code-formatting">RecyclerView</code> uses it. In future posts I will revisit some of these classes, write about them in detail and show you how to customize them for your project's needs.</p>
<h3>ViewHolder</h3>
<p><code class="preserve-code-formatting">ViewHolders</code> are basically caches of your <code class="preserve-code-formatting">View</code> objects. The Android team has been recommending using the ViewHolder pattern for a very long time, but they never actually enforced the use of it. Now with the new <code class="preserve-code-formatting">Adapter</code> you finally have to use this pattern.</p>
<p>It's a bit weird that Google waited so long to enforce the usage of the ViewHolder pattern, but better late than never. If you do not know about the ViewHolder pattern, have a look at this <a href="http://developer.android.com/training/improving-layouts/smooth-scrolling.html" title="Android training session using a ViewHolder">Android training session</a>. It uses the old <code class="preserve-code-formatting">Adapter</code>, but the pattern itself hasn't changed. </p>
<p>Also searching for ViewHolder should yield plenty of hits to further blog posts. For example this post by <a href="http://antoine-merle.com/listview-optimisations-part-1-the-viewholder/" title="Antoine Merle about using the ViewHolder to speed up your ListView">Antoine Merle about ListView optimizations</a>.</p>
<p>One thing that is specific to any <code class="preserve-code-formatting">RecyclerView.ViewHolder</code> subclass is that you can always access the root view of your <code class="preserve-code-formatting">ViewHolder</code> by accessing the public member <code class="preserve-code-formatting">itemView</code>. So there's no need to store that within your <code class="preserve-code-formatting">ViewHolder</code> subclass.</p>
<p>And should you decide to override <code class="preserve-code-formatting">toString()</code> have a look at the base class. Its <code class="preserve-code-formatting">toString()</code> implementation prints some useful information you should consider to use for your log messages as well.</p>
<p>Here's the code for the ViewHolder of the sample project. The ViewHolder is an inner class of the sample project's Adapter:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public final static class ListItemViewHolder extends RecyclerView.ViewHolder {
   TextView label;
   TextView dateTime;
   
   public ListItemViewHolder(View itemView) {
      super(itemView);
      label = (TextView) itemView.findViewById(R.id.txt_label_item);
      dateTime = (TextView) itemView.findViewById(R.id.txt_date_time);
   }
}</code></pre>
</div>
<h3>RecyclerView.Adapter</h3>
<p>Adapters fulfill two roles: They provide access to the underlying data set and they are responsible for creating the correct layout for individual items. Adapters always were part of Android and were used in many places. <code class="preserve-code-formatting">ListView</code>, <code class="preserve-code-formatting">AutoCompleteTextView</code>, <code class="preserve-code-formatting">Spinner</code> and more all made use of adapters. All those classes inherit from <code class="preserve-code-formatting">AdapterView</code>. But not so RecyclerView.</p>
<p>For the new <code class="preserve-code-formatting">RecyclerView</code> Google has decided to replace the old <a href="http://developer.android.com/reference/android/widget/Adapter.html" title="API documentation of the Adapter interface">Adapter</a> interface with a new <code class="preserve-code-formatting">RecyclerView.Adapter</code> base class. So say good bye to things like <code class="preserve-code-formatting">SimpleCursorAdapter</code>, <code class="preserve-code-formatting">ArrayAdapter</code> and the like. At least in their current incarnation. </p>
<p>Currently <strong>there is no default implementation</strong> of RecyclerView.Adapter available. Google might add some later on, but I wouldn't bet on this. For Animations to work properly, cursors and arrays aren't the best fit, so porting the current <code class="preserve-code-formatting">Adapter</code> implementations might not make too much sense.</p>
<p>Since <code class="preserve-code-formatting">RecyclerView.Adapter</code> is abstract you will have to implement these three methods:</p>
<ul>
<li><code class="preserve-code-formatting">public VH onCreateViewHolder(ViewGroup parent, int viewType)</code></li>
<li><code class="preserve-code-formatting">public void onBindViewHolder(VH holder, int position)</code></li>
<li><code class="preserve-code-formatting">public int getItemCount()</code></li>
</ul>
<p>The <code class="preserve-code-formatting">VH</code> in the method signatures above is the generic type parameter. You specify the concrete type to use when you subclass the <code class="preserve-code-formatting">RecyclerView.Adapter</code>. You can see this in line 3 of the next code sample.</p>
<p>The most basic adapter for the sample layout looks like this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public class RecyclerViewDemoAdapter extends 
        RecyclerView.Adapter
        &lt;RecyclerViewDemoAdapter.ListItemViewHolder&gt; {

    private List&lt;DemoModel&gt; items;

    RecyclerViewDemoAdapter(List&lt;DemoModel&gt; modelData) {
        if (modelData == null) {
            throw new IllegalArgumentException(
                  &quot;modelData must not be null&quot;);
        }
        this.items = modelData;
    }

    @Override
    public ListItemViewHolder onCreateViewHolder(
            ViewGroup viewGroup, int viewType) {
        View itemView = LayoutInflater.
                from(viewGroup.getContext()).
                inflate(R.layout.item_demo_01, 
                        viewGroup,
                        false);
        return new ListItemViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(
            ListItemViewHolder viewHolder, int position) {
        DemoModel model = items.get(position);
        viewHolder.label.setText(model.label);
        String dateStr = DateUtils.formatDateTime(
                viewHolder.label.getContext(),
                model.dateTime.getTime(),
                DateUtils.FORMAT_ABBREV_ALL);
        viewHolder.dateTime.setText(dateStr);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public final static class ListItemViewHolder 
           extends RecyclerView.ViewHolder {
        // ... shown above in the ViewHolder section
    }
}</code></pre>
</div>
<h3>RecyclerView.LayoutManager</h3>
<p>The <code class="preserve-code-formatting">LayoutManager</code> is probably the most interesting part of the <code class="preserve-code-formatting">RecyclerView</code>. This class is responsible for the layout of all child views. There is <strong>one default implementation</strong> available: <strong><code class="preserve-code-formatting">LinearLayoutManager</code></strong> which you can use for vertical as well as horizontal lists.</p>
<p>You have to set a <code class="preserve-code-formatting">LayoutManager</code> for your <code class="preserve-code-formatting">RecyclerView</code> otherwise you will see an exception at Runtime:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
08-01 05:00:00.000  2453  2453 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$LayoutManager.onMeasure(android.support.v7.widget.RecyclerView$Recycler, android.support.v7.widget.RecyclerView$State, int, int)' on a null object reference
08-01 05:00:00.000  2453  2453 E AndroidRuntime: 	at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1310)</code></pre>
</div>
<p>Only one method of <code class="preserve-code-formatting">LayoutManager</code> is currently abstract:</p>
<ul>
<li><code class="preserve-code-formatting">public LayoutParams generateDefaultLayoutParams()</code></li>
</ul>
<p>But there is another one where the code states that you should overrride it since it's soon going to be abstract:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public void scrollToPosition(int position) {
   if (DEBUG) {
      Log.e(TAG, &quot;You MUST implement scrollToPosition. It will soon become abstract&quot;);
   }
}</code></pre>
</div>
<p>That's very weird! Why not make it abstract right away? Anyway: Better you override this one to be on the safe side for when Google releases the final version of L.</p>
<p>But only overriding those two methods won't get you very far. After all the <code class="preserve-code-formatting">LayoutManager</code> is responsible for positioning the items you want to display. Thus you have to override <code class="preserve-code-formatting">onLayoutChildren()</code> as well. </p>
<p>This method also contains a log statement stating "You must override onLayoutChildren(Recycler recycler, State state)". Ok, then make it abstract <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Luckily there's still plenty (?) of time to change that into a proper abstract method for the final release of L. We all make mistakes. After all, <a href="http://www.grokkingandroid.com/tag/mistakes/" title="My series about my stupid decisions, mistakes and so on">my "Stupid stuff devs make" series</a> is all about blunders that I made. So don't get me wrong. No hard feelings here!</p>
<h4>LinearlayoutManager</h4>
<p>The <code class="preserve-code-formatting">LinearLayoutManager</code> is currently the only default implementation of <code class="preserve-code-formatting">LayoutManager</code>. You can use this class to create either vertical or horizontal lists.</p>
<p>The implementation of <code class="preserve-code-formatting">LinearLayoutManager</code> is rather complex and I only had a look at some key aspects. I will return to this implementation in my post about custom <code class="preserve-code-formatting">LayoutManagers</code>.</p>
<p>To use the <code class="preserve-code-formatting">LinearLayoutManager</code> you simply have to instantiate it, tell it which orientation to use and you are done:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.scrollToPosition(currPos);
recyclerView.setLayoutManager(layoutManager);</code></pre>
</div>
<p><code class="preserve-code-formatting">LinearLayoutManager</code> also offers some methods to find out about the first and last items currently on screen:</p>
<ul>
<li><code class="preserve-code-formatting">findFirstVisibleItemPosition()</code></li>
<li><code class="preserve-code-formatting">findFirstCompletelyVisibleItemPosition()</code></li>
<li><code class="preserve-code-formatting">findLastVisibleItemPosition()</code></li>
<li><code class="preserve-code-formatting">findLastCompletelyVisibleItemPosition()</code></li>
</ul>
<p>Surprisingly these methods are not part of the source code in the SDK folder, but you can use them as they are part of the binaries. As I cannot imagine those being removed, I'm sure you'll find these in the final L release as well.</p>
<p>Other methods help you get the orientation of the layout or the current scroll state. Others will compute the scroll offset. And finally you can reverse the ordering of the items.</p>
<p>Since I'm going to write an extra post about <code class="preserve-code-formatting">LayoutManagers</code> this should suffice for now.</p>
<h3>RecyclerView.ItemDecoration</h3>
<p>With an <code class="preserve-code-formatting">ItemDecoration</code> you can add an offset to each item and modify the item so that items are separated from each other, highlighted or, well, decorated.</p>
<p>You do not have to use an <code class="preserve-code-formatting">ItemDecoration</code>. If, for example, you use a <code class="preserve-code-formatting">CardView</code> for each item, there's no need for an ItemDecoration.</p>
<p>On the other hand you can add as many <code class="preserve-code-formatting">ItemDecorations</code> as you like. The <code class="preserve-code-formatting">RecyclerView</code> simply iterates over all <code class="preserve-code-formatting">ItemDecorations</code> and calls the respective drawing methods for each of them in the order of the decoration chain.</p>
<p>The abstract base class contains these three methods:</p>
<ul>
<li><code class="preserve-code-formatting">public void onDraw(Canvas c, RecyclerView parent)</code></li>
<li><code class="preserve-code-formatting">public void onDrawOver(Canvas c, RecyclerView parent)</code></li>
<li><code class="preserve-code-formatting">public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent)</code></li>
</ul>
<p>Anything you paint in <code class="preserve-code-formatting">onDraw()</code> might be hidden by the content of the item views but anything that you paint in <code class="preserve-code-formatting">onDrawOver()</code> is drawn on top of the items. If you simply create a bigger offset and, for example, use this offset to paint dividers, this of course is of no importance. But if you really want to add decorations, you have to use <code class="preserve-code-formatting">onDrawOver()</code>.</p>
<p>The <code class="preserve-code-formatting">LayoutManager</code> calls the <code class="preserve-code-formatting">getItemOffset()</code> method during the measurement phase to calculate the correct size of each item's views. The <code class="preserve-code-formatting">outRect</code> parameter might look a bit odd at first. Why not use a return value instead? But it really makes a lot of sense, since this allows <code class="preserve-code-formatting">RecyclerView</code> to reuse one <code class="preserve-code-formatting">Rect</code> object for all children and thus save resources. Not necessarily nice &mdash; but efficient.</p>
<p>One thing I didn't expect considering the name of the class is that the <code class="preserve-code-formatting">onDraw()</code>/<code class="preserve-code-formatting">onDrawOver()</code> methods are <strong>not</strong> called for each item, but just once for every draw operation of the <code class="preserve-code-formatting">RecyclerView</code>. You have to iterate over all child views of the <code class="preserve-code-formatting">RecyclerView</code> yourself.</p>
<p>I will explain this in more detail in a follow-up post about writing your own <code class="preserve-code-formatting">ItemDecorations</code>.</p>
<h3>RecyclerView.ItemAnimator</h3>
<p>The <code class="preserve-code-formatting">ItemAnimator</code> class helps the <code class="preserve-code-formatting">RecyclerView</code> with animating individual items. <code class="preserve-code-formatting">ItemAnimators</code> deal with three events:</p>
<ul>
<li>An item gets added to the data set</li>
<li>An item gets removed from the data set</li>
<li>An item moves as a result of one or more of the previous two operations</li>
</ul>
<p>Luckily there exists a <strong>default implementation aptly named DefaultItemAnimator</strong>. If you do not set a custom <code class="preserve-code-formatting">ItemAnimator</code>, <code class="preserve-code-formatting">RecyclerView</code> uses an instance of <code class="preserve-code-formatting">DefaultItemAnimator</code>.</p>
<p>Obviously for animations to work, Android needs to know about changes to the dataset. For this Android needs the support of your adapter. In earlier versions of Android you would call <code class="preserve-code-formatting">notifyDataSetChanged()</code> whenever changes occured, this is no longer appropriate. This method triggers a complete redraw of all (visible) children at once without any animation. To see animations you have to use more specific methods. </p>
<p>The RecyclerView.Adapter class contains plenty of <code class="preserve-code-formatting">notifyXyz()</code> methods. The two most specific are:</p>
<ul>
<li><code class="preserve-code-formatting">public final void notifyItemInserted(int position)</code></li>
<li><code class="preserve-code-formatting">public final void notifyItemRemoved(int position)</code></li>
</ul>
<p>The following video shows the result of an addition as well as a removal of an item in the sample app:</p>
<div style="width: 241px;" class="wp-video"><video class="wp-video-shortcode" id="video-2980-2" width="241" height="400" preload="metadata" controls="controls"><source type="video/mp4" src="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_animation.mp4?_=2" /><a href="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_animation.mp4">https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_animation.mp4</a></video></div>
<p class="caption short">A short video showing the default animations for the removal and addition of elements</p>
<h3>Listeners</h3>
<p><code class="preserve-code-formatting">RecyclerView</code> also offers some rather generic listeners. Once again you can safely forget everything you used to use up to now. There is no <code class="preserve-code-formatting">OnItemClickListener</code> or <code class="preserve-code-formatting">OnItemLongClickListener</code>. But you can use an <code class="preserve-code-formatting">RecyclerView.OnItemTouchListener</code> in combination with gesture detection to identify those events. A bit more work and more code to achieve the same result. I still hope for Google to add those Listeners in the final release. But whether those Listeners will be added is as an open question.</p>
<h3>Combining all classes</h3>
<p>You combine the classes either in a fragment or an activity. For the sake of simplicity my sample app uses activities only.</p>
<p>First of all here's the layout file containing the <code class="preserve-code-formatting">RecyclerView</code>:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;
    tools:context=&quot;.RecyclerViewDemoActivity&quot;&gt;

    &lt;android.support.v7.widget.RecyclerView
        android:id=&quot;@+id/recyclerView&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        tools:context=&quot;.MainActivity&quot;
        tools:listitem=&quot;@layout/item_demo_01&quot;
        /&gt;

    &lt;ImageButton
        android:id=&quot;@+id/fab_add&quot;
        android:layout_alignParentRight=&quot;true&quot;
        android:layout_alignParentBottom=&quot;true&quot;
        android:layout_width=&quot;@dimen/fab_size&quot;
        android:layout_height=&quot;@dimen/fab_size&quot;
        android:layout_gravity=&quot;bottom|right&quot;
        android:layout_marginRight=&quot;16dp&quot;
        android:layout_marginBottom=&quot;16dp&quot;
        android:background=&quot;@drawable/ripple&quot;
        android:stateListAnimator=&quot;@anim/anim&quot;
        android:src=&quot;@drawable/ic_action_add&quot;
        android:elevation=&quot;1dp&quot;
        /&gt;
&lt;/RelativeLayout&gt;</code></pre>
</div>
<p>As you can see, nothing special here. You do not define the orientation or stuff like that on the <code class="preserve-code-formatting">RecyclerView</code>. Actually <code class="preserve-code-formatting">RecyclerView</code> itself makes no use of the attributes, it passes them on to the parent (which is <code class="preserve-code-formatting">ViewGroup</code>) and that's it.</p>
<p>There is one place within RecyclerView where an <code class="preserve-code-formatting">AttributeSet</code> is used and that is in the <code class="preserve-code-formatting">generateLayoutParams()</code> method:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
   if (mLayout == null) {
      throw new IllegalStateException(&quot;RecyclerView has no LayoutManager&quot;);
   }
   return mLayout.generateLayoutParams(getContext(), attrs);
}</code></pre>
</div>
<p>In this snippet the <code class="preserve-code-formatting">RecyclerView</code> passes the <code class="preserve-code-formatting">AttributeSet</code> on to the <code class="preserve-code-formatting">LayoutManager</code>.</p>
<p>The Java code is also pretty simple:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
setContentView(R.layout.activity_recyclerview_demo);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.scrollToPosition(0);
recyclerView.setLayoutManager(layoutManager);

// allows for optimizations if all item views are of the same size:
recyclerView.setHasFixedSize(true);

// For the sake of simplicity I misused the Application subclass as a DAO
List&lt;DemoModel&gt; items = RecyclerViewDemoApp.getDemoData();
adapter = new RecyclerViewDemoAdapter(items);
recyclerView.setAdapter(adapter);

RecyclerView.ItemDecoration itemDecoration =
        new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);

// this is the default; 
// this call is actually only necessary with custom ItemAnimators
recyclerView.setItemAnimator(new DefaultItemAnimator());

// onClickDetection is done in this Activity's OnItemTouchListener
// with the help of a GestureDetector;
// Tip by Ian Lake on G+ in a comment to this post:
// https://plus.google.com/+LucasRocha/posts/37U8GWtYxDE
recyclerView.addOnItemTouchListener(this);
gesturedetector =
        new GestureDetectorCompat(this, new RecyclerViewDemoOnGestureListener());</code></pre>
</div>
<p>Connecting all those elements together roughly consists of these steps:</p>
<ol>
<li>Get a reference to your <code class="preserve-code-formatting">RecyclerView</code></li>
<li>Create a <code class="preserve-code-formatting">LayoutManager</code> and add it</li>
<li>Create an <code class="preserve-code-formatting">Adapter</code> and add it</li>
<li>Create zero or more <code class="preserve-code-formatting">ItemDecorations</code> as needed and add them</li>
<li>Create an <code class="preserve-code-formatting">ItemAnimator</code> if needed and add it</li>
<li>Create zero or more listeners as needed and add them</li>
</ol>
<p>All in all about 30 lines of code.</p>
<p>Now of course this is misleading. That's only the glue code. The really interesting stuff is in <code class="preserve-code-formatting">RecyclerView&#039;s</code> many inner classes which you can subclass and tweak to your needs. That's where the real work is done.</p>
<p>But the separation of concerns Google created helps you stick to one task within one implementation and it should make reuse easier to achieve. That's why I like <code class="preserve-code-formatting">RecyclerView</code> and its ecosystem. I'm not afraid to criticize big G, but that's well done, Google!</p>
<h3>Gradle integration</h3>
<p>To use RecyclerView you have to add it to your gradle file. Adding the support library alone is not enough:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
dependencies {
   //...
   compile 'com.android.support:recyclerview-v7:+'
   //...
}</code></pre>
</div>
<h3>Is that the final API?</h3>
<p>Of course I do not know if the concrete implementations that the preview contains will be in the final release of Android L. But I guess so. And I expect some additions as well as minor changes to the API, based on bug reports and developer feedback.</p>
<p>Google itself gives one hint in the current API documentation about more stuff to come. The documentation for the <code class="preserve-code-formatting">RecyclerView.LayoutManager</code> class contains this nugget:</p>
<blockquote><p>Several stock layout managers are provided for general use.</p></blockquote>
<p>So we <em>can</em> expect more LayoutManagers. Which, of course, is good. Furthermore I expect at least one default ItemDecoration as well. After all the support library's sample project contains a <code class="preserve-code-formatting">DividerItemDecoration</code>, which works well with the <code class="preserve-code-formatting">LinearLayoutManager</code>.</p>
<p>I'm more skeptical about adapters. While an <code class="preserve-code-formatting">ArrayAdapter</code> (or better yet, <code class="preserve-code-formatting">ListAdapter</code>) is very well possible, I am more doubtful about a <code class="preserve-code-formatting">CursorAdapter</code> since cursors do not lend themself easily to the new addition and removal notifications within the <code class="preserve-code-formatting">Adapter</code>.</p>
<h3>Lucas Rocha's TwoWayView to simplify your life</h3>
<p>I strongly recommend to have a look at <a href="https://github.com/lucasr/twoway-view" title="TwoWayView's project page at github">Lucas Rocha's TwoWayView project</a>. He has updated his project to work with <code class="preserve-code-formatting">RecyclerView</code> and has done a great deal to make using <code class="preserve-code-formatting">RecyclerView</code> a lot easier. For many use cases the default layouts he provides should suffice. And he also provides support for custom <code class="preserve-code-formatting">LayoutManagers</code>. Which are simpler to write using his framework than with the base <code class="preserve-code-formatting">RecyclerView</code>.</p>
<p>Take a look at his project and check out if it covers all you need. Using it helps you get rid of some of <code class="preserve-code-formatting">RecyclerView</code>'s complexity.</p>
<p>For more information about his project see his blog post about <a href="http://lucasr.org/2014/07/31/the-new-twowayview/" title="Lucas Rocha'S post about TwoWayView and its included LayoutManagers">how TwoWayView extends and simplifies RecyclerView</a>.</p>
<p>To learn about news about this project <a href="https://plus.google.com/u/0/+LucasRocha" title="Lucas Rocha's profile page on Google plus">follow Lucas Rocha on Google plus</a> or <a href="https://twitter.com/lucasratmundo" title="Lucas Rocha's Twitter account">Twitter</a>.</p>
<p>I will cover TwoWayView in this series as well - so stay tuned <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Report bugs!</h3>
<p>We currently have a developer preview. The first time Google does this for Android. Really nice. But of course this preview is not free of bugs. To help us all get a more stable final release, <a href="https://code.google.com/p/android-developer-preview/wiki/FilingIssues?tm=3" title="Issue Tracker for the L preview">give feedback or issue bug reports</a>, if you encounter anything that bothers you or is a bug. There is a special <a href="https://code.google.com/p/android-developer-preview/wiki/FilingIssues?tm=3" title="Issue tracker for the L preview">L preview issue tracker</a>.</p>
<h3>And that's it for today</h3>
<p>I started this post as part of the preparation for my talk at the July meetup of the <a href="http://www.dutchaug.org" title="Homepage of the Dutch Android User Group">Dutch Android User Group</a>. </p>
<p>I had much fun presenting about this topic at the July meetup of the Dutch Android User Group. And I had fun digging into this topic - and still have. Reading the source of RecyclerView and its many inner classes is really interesting. Thanks to the organizers for giving me the opportunity to speak about this topic and for forcing me to dig into this stuff <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>At Utrecht I had 15-20 minutes for <a href="https://speakerdeck.com/writtmeyer/new-views-in-android-l" title="The slides of my talk about RecyclerView in Utrecht">my talk</a>. How I managed to get it done in time is still a mystery to me. As you can see there's a lot to talk about - and this post is only the beginning.</p>
<p>Until next time!</p>
<p>The post <a href="https://www.grokkingandroid.com/first-glance-androids-recyclerview/">A First Glance at Android&#8217;s RecyclerView</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/first-glance-androids-recyclerview/feed/</wfw:commentRss>
			<slash:comments>72</slash:comments>
		
		<enclosure url="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/08/recyclerview_animation.mp4" length="143518" type="video/mp4" />

			</item>
		<item>
		<title>About Cyril Mottier&#8217;s &#8220;Shaping the Future of Android With Dart&#8221; &#8211; Some Additional Thoughts</title>
		<link>https://www.grokkingandroid.com/android-dart-additional-thoughts/</link>
					<comments>https://www.grokkingandroid.com/android-dart-additional-thoughts/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Fri, 13 Jun 2014 12:41:06 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2962</guid>

					<description><![CDATA[<p>This post is inspired by Cyril Mottier's post about Dart for Android. If you haven't read it already, please read it first. Mostly I think Cyril's arguments are valid. I wouldn't object to another language besides Java. Especially since the ability to use the new features of Java 8 might still be far away on [...]&#160;&#160;<a href="https://www.grokkingandroid.com/android-dart-additional-thoughts/">Continue Reading&#160;&#160;"About Cyril Mottier&#8217;s &#8220;Shaping the Future of Android With Dart&#8221; &#8211; Some Additional Thoughts"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/android-dart-additional-thoughts/">About Cyril Mottier&#8217;s &#8220;Shaping the Future of Android With Dart&#8221; &#8211; Some Additional Thoughts</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This post is inspired by <a href="https://plus.google.com/+CyrilMottier" title="Cyril Mottier's Google plus page">Cyril Mottier's</a> post about <a href="http://cyrilmottier.com/2014/06/12/shaping-the-future-of-android-with-dart/" title="Cyril Mottier's post about Dart for Android">Dart for Android</a>. If you haven't read it already, <a href="http://cyrilmottier.com/2014/06/12/shaping-the-future-of-android-with-dart/" title="Cyril's post about Dart for Android">please read it first</a>. </p>
<p>Mostly I think Cyril's arguments are valid. </p>
<p>I wouldn't object to another language besides Java. Especially since the ability to use the new features of Java 8 might still be far away on Android. </p>
<p>But what about Scala, Groovy or the like, you might ask. Well, I think Dart being a first class, Google supported citizen would be another matter altogether. Despite the fact that I agree mostly with Cyril's post, I think the post needs some kind of reply. And as much as I love Google plus, I think it's not the appropriate forum for my reply. So I stick to my old-fashioned blog - with it's even more old-fashioned look <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>I do not know whether Dart is a superb language. I only have had quick perfunctory glances on slides or the odd look at the <a href="https://www.dartlang.org" title="Official website of Dart">dartlang.org</a> website whenever the topic Dart crept up. I also missed the Google Dart flight school this winter and haven't develop anything decent in Dart at all. Yet from what I've read it looks like a decent enough and modern language that I would like to dig into. So Google bringing it to Android? That would be a very good reason for me to finally have a deeper look <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>What's important: Whatever Google comes up with, I strongly believe it's going to run on ART. I wouldn't be too surprised to learn that the initial reason to create a new VM in the first place, was inspired by Google's wish to support other languages better. But as everything in this post, that's just mere speculation. Pure guesswork.</p>
<p>There is a big reason for this: It's the easiest path to migration. It allows people to keep using existing libraries (no matter whether those are plain old Java libraries or specific Android library projects). If those libraries couldn't be used anymore, any other language would have a very difficult start.</p>
<p>It might also allow different teams of bigger organizations (think Facebook, Twitter, or those over-careful and very slow-movers like banks and insurances) to use both languages for one app (or app family). The hip front end team already uses Dart while those taking care of the database, synchronization and what not, keep using Java (for the time being). Cyril left this one very vague. I can't understand why? For me that's a necessity. Without it there's no successful path to a quick adoption. </p>
<p>If there is one thing, where I didn't agree with Cyril, it's his paragraph, where he suggests that Dart could be <em>the one</em> language for all of Google's projects. Such that Google could get rid of Python, Java, C++ and whatever else they use. I don't think that's feasible. For two reasons:</p>
<ol>
<li>
The question of existing libraries exists for Google projects as well. Of course Google could reinvent the wheel all the time - they have enough people to do so. But that would be a foolish waste of energy. I don't think it's likely that Google is going to do that.
</li>
<li>
One language is rarely suited for all kind of development efforts. That was never true for Java, has never been true for C and probably is not true for Dart as well. For one it's a VM language again. So whenever Google used C or C++ instead of Java or anything else, they will continue to do so instead of using Dart. And there's also the matter of the existing code base and libraries only in use within Google itself. Maybe my knowledge of Dart is too superficial to see how to do that efficiently with Dart. So that reason might not be valid at all. But my guess is, that it is.
</li>
</ol>
<p>And <a href="https://code.google.com/p/dart/issues/detail?id=19266" title="Issue 19266 about Dart support for Android">don't forget to star issue 19266</a> if you want to see Dart on Android.</p>
<p>One last thing: Generally speaking: I hate speculations. So me taking part at a speculative rumour mill, is a big exception. Let me know if you like this kind of post. And of course, what you think about this topic. I'm interested in what you've got to say. Am I totally off? Does this sound reasonable? Is it worth speculating at all? </p>
<p>The post <a href="https://www.grokkingandroid.com/android-dart-additional-thoughts/">About Cyril Mottier&#8217;s &#8220;Shaping the Future of Android With Dart&#8221; &#8211; Some Additional Thoughts</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/android-dart-additional-thoughts/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>Stupid mistakes devs make, part I: Taking app messages at face value</title>
		<link>https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/</link>
					<comments>https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Fri, 28 Feb 2014 06:45:11 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Error Messages]]></category>
		<category><![CDATA[Mistakes]]></category>
		<category><![CDATA[Programming]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2924</guid>

					<description><![CDATA[<p>This is a new series about programming blunders I make. Stuff that keeps me looking for solutions in all the wrong places while the answer most often is glaringly simple. If only I knew that right away! I am sorry for the generalization in the headline - of course it's only me doing stupid stuff [...]&#160;&#160;<a href="https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/">Continue Reading&#160;&#160;"Stupid mistakes devs make, part I: Taking app messages at face value"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/">Stupid mistakes devs make, part I: Taking app messages at face value</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>This is a new series about programming blunders I make. Stuff that keeps me looking for solutions in all the wrong places while the answer most often is glaringly simple. If only I knew that right away! </p>
<p>I am sorry for the generalization in the headline - of course it's only me doing stupid stuff like that <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Mistake of the day</h3>
<p>Yesterday I was happily coding the sharing action for my upcoming app. This particular ShareActionProvider of the app lets users share a picture of their progress with keeping bad habits in check. I create an image and make it available to other apps via a <code class="preserve-code-formatting">content://</code> Uri. Nothing spectacular about that.</p>
<p>You might know that the Email app asks your ContentProvider for the display name and the file size of the shared image. The image in question is about 20K in size. That's  far from being an overly big picture. Nevertheless I got the message that the attachment was too large:</p>
<figure id="attachment_2932" aria-describedby="caption-attachment-2932" style="width: 238px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/too_large_to_attache.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/too_large_to_attache.png" alt="Toast showing that the attachment was too large" width="238" height="48" class="size-full wp-image-2932" /></a><figcaption id="caption-attachment-2932" class="wp-caption-text">Toast showing that the attachment was too large</figcaption></figure>
<p>This left me wondering, what might possibly be wrong. I looked at the log messages. Check. I looked at the size of the stored image. Check. I debugged into my content provider to see that it reported the correct file size. Check. Starting to go out of ideas I even adb pulled the file and opened it in an image viewer. Check - it indeed was an image. I had another look at logcat. Check. All fine. So what the heck... My curse level had increased considerably! Never a good sign.</p>
<p>But wait a moment. One of those checks above was not correct. Actually <strong>two</strong> of those were not correct. And - to be honest - just assuming that the message of the Email app was correct, probably was the first mistake. It totally misled me - and even worse: I let it do that.</p>
<p>Finally I looked a bit more carefully. It turns out that I stopped debugging my content provider too early. And that I grepped logcat too rigorously.</p>
<p>My content provider crashed shortly after the line where I stopped debugging, assuming everything to be perfectly fine. This assumption proved to be very wrong, since my code ran into a <code class="preserve-code-formatting">ClassCastException</code> <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>And I didn't see it in logcat because I renamed my package a few days ago, but didn't rename my logging tag. The tag was the final part of the <em>old</em> app package name. And I grepped only for this tag - which proved to be very stupid! With this clever way of grepping any hints of stacktraces were gone.</p>
<p>Finally: I didn't notice this problem in any tests, because I do not work test first and simply had no tests for the sharing part of my provider.</p>
<p>BTW: I do neither get the "File too large to attach" message on an old API level 8 device, nor on my GNex or my N5. Alas I had my Nexus 7 used for testing, which I update rarely since it's a testing device only. The Email app seems to have been fixed. So with any of my other testing devices, I probably wouldn't have had the same problems. It was just one of those days <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f641.png" alt="🙁" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Lessons learned</h3>
<p>Actually running into stuff like this is not all bad. Okay, granted: It is. I wasted too much time with it. But the good part is, that it's just another lesson along the way. And a lesson I probably won't forget that soon.</p>
<p>For this day my takeaways were:</p>
<ul>
<li>Do not trust messages of other apps</li>
<li>Do not rename packages without renaming logcat tags as well</li>
<li>Stop being so sloppy with your tests</li>
</ul>
<p>That's it for today. The next post in this series will have the name "Be careful with that package name, Eugene". Obviously it nicely fits the scheme of this post since it's just another package name mishap.</p>
<p>Have you experienced anything like that? If so, please let us know in the comments. Don't let me be the only fool around <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/">Stupid mistakes devs make, part I: Taking app messages at face value</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/stupid-mistakes-dev-make-part_i/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>An XMPP Server for Google Cloud Messaging</title>
		<link>https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/</link>
					<comments>https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Tue, 18 Feb 2014 06:29:24 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CCS]]></category>
		<category><![CDATA[Cloud Connection Server]]></category>
		<category><![CDATA[Google Cloud Messaging]]></category>
		<category><![CDATA[XMPP]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2827</guid>

					<description><![CDATA[<p>In this post I am going to write about the server-side of upstream messages with Google Cloud Messaging. This is the second part of my three-part series on this topic. If you haven't read the first part about the flow of events and the Android implementation of upstream messaging, please read that one first. The [...]&#160;&#160;<a href="https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/">Continue Reading&#160;&#160;"An XMPP Server for Google Cloud Messaging"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/">An XMPP Server for Google Cloud Messaging</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this post I am going to write about the server-side of upstream messages with Google Cloud Messaging. This is the second part of my three-part series on this topic. If you haven't read the first <a href="http://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/" title="Upstream Messages With Google Cloud Messaging">part about the flow of events and the Android implementation of upstream messaging</a>, please read that one first. The first sections of that post are important to understand the big picture of upstream messaging and the role of the server within it. </p>
<h3>Sample project</h3>
<p>I have created a <a href="https://github.com/writtmeyer/gcm_server" title="Sample server project for using the Cloud Connection Server">sample project for the server side of upstream messaging</a> with Google Cloud Messaging. Please note that this is a <em>sample</em>. It's not suitable for production!</p>
<h3>Permanent connection and XMPP</h3>
<p>Just recall the flow of events, described in detail in my first post:</p>
<figure id="attachment_2835" aria-describedby="caption-attachment-2835" style="width: 300px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs-300x242.png" alt="The communication model of Google Cloud Messaging with the new Cloud Connection Server" width="300" height="242" class="size-medium wp-image-2835" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs-300x242.png 300w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs.png 900w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2835" class="wp-caption-text">The communication model of Google Cloud Messaging with the new GCM Cloud Connection Server</figcaption></figure>
<p>For this flow to work, Google must contact your server whenever the user sends a message from his device upstream to Google's cloud. There are many models of how to do that. The one chosen by Google is to require a permanent connection between your backend and one of Google's endpoints.</p>
<p>That's where XMPP comes into play. Google has chosen XMPP as the protocol of choice for communicating between its servers and your server. Google named its XMPP endpoint "GCM Cloud Connection Server" or CCS for short. XMPP is an XML-based protocol that was created for instant messaging (also known under it's original name Jabber). You can read <a href="http://en.wikipedia.org/wiki/XMPP" title="XMPP page on Wikipedia">more about XMPP on Wikipedia</a>.</p>
<h3>Server side code</h3>
<p>In the <a href="http://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/" title="First post about upstream messages With Google Cloud Messaging">previous post about upstream messaging</a> you have seen that the Android side of GCM messaging is as simple as it can get.</p>
<p>The server side though is another matter altogether and got more complicated with the new solution.</p>
<p>First of all you're most likely not as familiar with XMPP as you are with HTTP. And you're not alone with it. HTTP is probably the most used application layer protocol. Thus the online knowledge base for HTTP is huge. Less so for XMPP. You probably have to search longer for solutions when hitting a stumbling block with XMPP. </p>
<p>This situation also applies to libraries. While there is an abundance of HTTP libraries, there are way less for XMPP. For Java I have found only one library that is still actively maintained: The <a href="http://www.igniterealtime.org/projects/smack/" title="Smack Library: XMPP library for Java">Smack library</a>, which Google also uses in its sample code. </p>
<p>Luckily Google has a very <a href="https://developer.android.com/google/gcm/ccs.html" title="Google's CCS page describing all message types">detailed description of all the message types</a> exchanged between your server and Google's cloud. And since XMPP is text-based you could build a client on your own - no matter which language you use. Nevertheless I recommend to <strong>use a library</strong> for this - after all they not only ease your life but are also more heavily tested. It's likely that others already have found a solution for a problem that would otherwise bite you in production when writing your own code.</p>
<p>I have taken <a href="http://developer.android.com/google/gcm/ccs.html#smack" title="Google's Smack based sample code for using GCM with XMPP">Google's sample code for XMPP</a> and extended it to be more flexible and suit my needs. This code requires the <a href="http://www.igniterealtime.org/projects/smack/" title="Project page of the Smack library">Smack</a> and the <a href="http://code.google.com/p/json-simple/" title="Project page of the json-simple library">json-simple</a> libraries. To repeat: The demo is there just to get you up and running, so that you can easily test the upstream messaging model and your Android code. It's still very basic and rough!</p>
<h3>Logging messages</h3>
<p>When setting up the connection using Smack's <code class="preserve-code-formatting">XMPPConnection</code>, you can configure it to open a Swing window displaying all incoming and outgoing messages:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
config.setDebuggerEnabled(mDebuggable);</code></pre>
</div>
<p>I set the flag to true when using the <code class="preserve-code-formatting">main()</code> method of <code class="preserve-code-formatting">CcsClient</code>. That obviously wouldn't work too well on a server so I made this configurable. From within my web project I set this flag to <code class="preserve-code-formatting">false</code>.</p>
<p>There is another flag that configures if Smack logs every message:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
XMPPConnection.DEBUG_ENABLED = true;</code></pre>
</div>
<p>Within the sample code I simply set this to true to see every message. Very handy for finding problems during development and appropriate for this demo project.</p>
<h3>Implementing a server</h3>
<p>These are the things you have to take care of:</p>
<ul>
<li>Establish the connection</li>
<li>Authenticate your server app</li>
<li>Receive messages from Google's cloud</li>
<li>Send messages to Google's cloud</li>
<li>Acknowledge messages</li>
<li>Deal with problems</li>
</ul>
<p>Since all message types are described in detail on <a href="http://www.grokkingandroid.com/firefoxos-initial-impression/" title="Google's CCS page describing all message types">Google's Cloud Connection Server page</a>, you can use whatever solution you like. The following code samples are in Java and make use of the Smack library. While some stuff is from Google's sample code, some contains additions and abstractions around that sample code.</p>
<p>The most important class is <a href="https://github.com/writtmeyer/gcm_server/blob/master/src/com/grokkingandroid/sampleapp/samples/gcm/ccs/server/CcsClient.java" title="The source code of the adapted CcsClient of the sample app">CcsClient</a>. This class is responsible for logging in to the server, sending messages to Google's Cloud, receiving incoming messages and handling ACKs and NACKs correctly.</p>
<h3>Connect to the GCM Cloud Connection Server</h3>
<p>For the permanent connection you open a TLS secured connection to <code class="preserve-code-formatting">gcm.googleapis.com</code> at port 5235. </p>
<p>Within <code class="preserve-code-formatting">CcsClient</code> the method <code class="preserve-code-formatting">connect()</code> handles this. It needs a <a href="http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/org/jivesoftware/smack/ConnectionConfiguration.html" title="Documentation of the class ConnectionConfiguration of the Smack library">ConnectionConfiguration</a> object. </p>
<p>Here's how to set up the <code class="preserve-code-formatting">ConnectionConfiguration</code>:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(true);
config.setRosterLoadedAtLogin(false);
config.setSendPresence(false);
config.setSocketFactory(SSLSocketFactory.getDefault());</code></pre>
</div>
<p>In the first line you specify which server and which port to use. As mentioned these have to be <code class="preserve-code-formatting">gcm.googleapis.com</code> and <code class="preserve-code-formatting">5235</code> respectively. And you have to ensure to use Transport Layer Security (TLS). That's why you have to set the <code class="preserve-code-formatting">SSLSocketFactory</code>.</p>
<p>Afterwards you can create a <a href="http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/index.html?org/jivesoftware/smack/Connection.html" title="Documentation of Smack's Connection object">Connection</a> object and use it to establish the connection to Google's servers:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
Connection connection = new XMPPConnection(config);
connection.connect();</code></pre>
</div>
<h3>Authenticate your server app</h3>
<p>Google needs to ensure that you are allowed to send messages via Google Cloud Messaging - and that you are allowed to send them to the clients you are addressing. For this Google uses a project id and an API key specific for that Google Cloud project.</p>
<p>I have detailed in my previous post about upstream messaging <a href="http://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/" title="Upstream messaging post that details how to create a cloud project and the API keys">how to create a project and how to generate a server API key for that project</a>. </p>
<p>With XMPP you do not send the API key with every request. Instead you authenticate your server app directly after establishing the connection.</p>
<p>In Java just use the <code class="preserve-code-formatting">Connection</code> object you created in the previous step to log in:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
connection.login(mProjectId + &quot;@gcm.googleapis.com&quot;, mApiKey);</code></pre>
</div>
<p>Obviously you have to use the values created on Google's Cloud Console for <code class="preserve-code-formatting">mProjectId</code> and <code class="preserve-code-formatting">mApiKey</code>. You either pass them as arguments to the <code class="preserve-code-formatting">main()</code> method of <code class="preserve-code-formatting">CcsClient</code> or you call <code class="preserve-code-formatting">prepareClient()</code> with the correct values - which I do from within my web project.</p>
<p>After logging in, you can send and receive messages.</p>
<h3>Message formats</h3>
<p>Before I will cover how to send or receive messages, I'm going to show you some typical messages sent either from your server or back to your server.</p>
<h4>Incoming upstream messages</h4>
<p>The following is a message as it shows up on your server when a user clicks "Register" in the <a href="https://github.com/writtmeyer/gcm_sample" title="Github page of  my Google Cloud Messaging sample app"></a>Android client sample</a>:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;message 
      to=&quot;projectId@gcm.googleapis.com&quot; 
      from=&quot;devices@gcm.googleapis.com&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
      {
      &quot;category&quot;:&quot;com.grokkingandroid.sampleapp.samples.gcm&quot;,
      &quot;data&quot;:
         {
         &quot;action&quot;:
            &quot;com.grokkingandroid.sampleapp.samples.gcm.REGISTER&quot;,
         &quot;account&quot;:&quot;info@openminds.de&quot;
         },
      &quot;message_id&quot;:&quot;20&quot;,
      &quot;from&quot;:&quot;someRegistrationId&quot;
      }
   &lt;/gcm&gt;
&lt;/message&gt;</code></pre>
</div>
<p>This message is no different from any other message sent from an Android device. It is obvious that the message consists of an outer XML part and an inner JSON part. You can safely ignore the XML part. It's always the same and is only used since XMPP is an XML based protocol. What's important is the JSON part. The JSON object contains all the attributes you need to react appropriately to incoming messages.</p>
<p>All upstream messages contain the following attributes:</p>
<table>
<caption>The attributes of a received GCM upstream message</caption>
<tr>
<th>Attribute</th>
<th>Meaning</th>
</tr>
<tr>
<td>category</td>
<td>Package name of the sending app</td>
</tr>
<tr>
<td>data</td>
<td>The payload of your app</td>
</tr>
<tr>
<td>message_id</td>
<td>A unique id you need later on to acknowledge the message</td>
</tr>
<tr>
<td>from</td>
<td>The registration id of the device from which the message was sent</td>
</tr>
</table>
<p>Obviously only your apps can send data to your server. But you can use the same GCM server for multiple apps. That's why the <code class="preserve-code-formatting">category</code> attribute is needed.</p>
<p>The <code class="preserve-code-formatting">data</code> attribute is where you can put all the stuff, that you want to transmit to your server. The value of the <code class="preserve-code-formatting">data</code> attribute is a JSON object itself.</p>
<p>The registration id is sent with every message within the <code class="preserve-code-formatting">from</code> attribute. It's a very lengthy string which you must use to map the data to the correct user. </p>
<h4>ACK messages</h4>
<p>The next section explains what's up with the ACK and NACK messages. For now, you just need to know what those messages look like.</p>
<p>An ACK message is the simpler of both and always looks the same:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;message&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
      {
      &quot;message_id&quot;:&quot;m-8238983812089683316&quot;,
      &quot;message_type&quot;:&quot;ack&quot;,
      &quot;from&quot;:&quot;someRegistrationId&quot;
      }
   &lt;/gcm&gt;
&lt;/message&gt;</code></pre>
</div>
<table>
<caption>The attributes of an ACK message</caption>
<tr>
<th>Attribute</th>
<th>Meaning</th>
</tr>
<tr>
<td>from</td>
<td>The registration id to which the message was sent</td>
</tr>
<tr>
<td>message_id</td>
<td>The id of the message, that is acknowledged</td>
</tr>
<tr>
<td>message_type</td>
<td>ACK or NACK - for ACK messages obviously always "<code class="preserve-code-formatting">ack</code>"</td>
</tr>
</table>
<h4>Incoming NACK messages</h4>
<p>NACK messages come in two types. A stanza message always indicates a malformed message on your side. Stanza is the weird name used in the XMPP specification for the different kinds of XML messages that XMPP supports. Any other erroneous condition is handled by the second type of NACK messages.</p>
<p>Let me show you a stanza message first:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;message 
      id=&quot;iUB3B-2&quot; 
      to=&quot;someProjectId@gcm.googleapis.com&quot; 
      type=&quot;error&quot;&gt;
   &lt;error 
         code=&quot;400&quot; 
         type=&quot;MODIFY&quot;&gt;
      &lt;bad-request 
            xmlns=&quot;urn:ietf:params:xml:ns:xmpp-stanzas&quot;/&gt;
      &lt;text 
            xml:lang=&quot;en&quot; 
            xmlns=&quot;urn:ietf:params:xml:ns:xmpp-stanzas&quot;&gt;
            InvalidJson: JSON_PARSING_ERROR
                  : Missing Required Field: message_id
      &lt;/text&gt;
   &lt;/error&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
      {
      &quot;to&quot;:&quot;someRegId&quot;,
      &quot;delay_while_idle&quot;:true,
      &quot;data&quot;:
         {
         &quot;message&quot;:
               &quot;Simple sample sessage&quot;
         },
      &quot;time_to_live&quot;:120000
      }
   &lt;/gcm&gt;
&lt;/message&gt;</code></pre>
</div>
<p>The <code class="preserve-code-formatting">error</code> element of the XML message contains the description of what went wrong. And the <code class="preserve-code-formatting">gcm</code> element contains the complete message you have sent to the server. The descriptive error message together with the full message causing the problem makes it really simple to understand what went wrong. In this case, the <code class="preserve-code-formatting">message_id</code> is missing. I won't go into detail for this type. You get those messages only, if you do not provide all mandatory attributes.</p>
<p>Stanza error messages should only happen while developing your app. What might follow later on are other problem types. Here is a sample message for other failure situations:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;message&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
      {
      &quot;message_id&quot;:&quot;m-4370299872608467243&quot;,
      &quot;from&quot;:&quot;invalidRegId&quot;,
      &quot;error&quot;:&quot;BAD_REGISTRATION&quot;,
      &quot;message_type&quot;:&quot;nack&quot;
      }
   &lt;/gcm&gt;
&lt;/message&gt;</code></pre>
</div>
<p>In this case the registration id you sent to Google's server is invalid. Note: You will also get NACK messages for as long as your sign-up form hasn't been processed by Google.</p>
<table>
<caption>The attributes of a NACK message</caption>
<tr>
<th>Attribute</th>
<th>Meaning</th>
</tr>
<tr>
<td>error</td>
<td>A short error message</td>
</tr>
<tr>
<td>from</td>
<td>The registration id to which the message was sent</td>
</tr>
<tr>
<td>message_id</td>
<td>The id of the message, that is acknowledged</td>
</tr>
<tr>
<td>message_type</td>
<td>ACK or NACK - for NACK messages obviously always "<code class="preserve-code-formatting">nack</code>"</td>
<p></tR><br />
</table>
<h4>Outgoing messages to devices</h4>
<p>The final message type is a message from your server to an Android device:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;message id=&quot;4icfN-5&quot;&gt;
   &lt;gcm xmlns=&quot;google:mobile:data&quot;&gt;
      {
      &quot;to&quot;:&quot;someRegistrationId&quot;,
      &quot;delay_while_idle&quot;:true,
      &quot;data&quot;:
         {
         &quot;message&quot;:&quot;Test message to a registered device&quot;
         },
      &quot;message_id&quot;:&quot;m-15&quot;,
      &quot;time_to_live&quot;:10000
      }
   &lt;/gcm&gt;
&lt;/message&gt;</code></pre>
</div>
<p>Some of the attributes for sending messages via the Cloud Connection Server are the same as with messages via Google's HTTP server. Others though are new and still others are missing. The following table shows a list of all possible attributes for sending XMPP messages to a device.</p>
<table>
<caption>The attributes of a push message</caption>
<tr>
<th>Attribute</th>
<th>Meaning</th>
<th>Mandatory</th>
</tr>
<tr>
<td>collapse_key</td>
<td>A key indicating that only the last message of this type should be sent to a device when it comes online again</td>
<td>No</td>
</tr>
<tr>
<td>data</td>
<td>The payload of your app</td>
<td>No</td>
</tr>
<tr>
<td>delay_while_idle</td>
<td>A flag indicating that messages should be kept on Google's server if the device is inactive</td>
<td>No</td>
</tr>
<tr>
<td>message_id</td>
<td>A unique id you need later when dealing with ACK and NACK messages</td>
<td>Yes</td>
</tr>
<tr>
<td>time_to_live</td>
<td>The amount of time for which Google should keep the message around if the device is offline</td>
<td>No</td>
</tr>
<tr>
<td>to</td>
<td>The registration id of the recipient</td>
<td>Yes</td>
</tr>
</table>
<p>If you have used GCM in the past you will notice the <code class="preserve-code-formatting">to</code> attribute. That's the XMPP replacement for <code class="preserve-code-formatting">registration_ids</code>. And in contrast to <code class="preserve-code-formatting">registration_ids</code> you can send a message to only one user. Which means that for a broadcast you have to iterate over all registration ids. <a href="https://developer.android.com/google/gcm/server.html" title="Google's documentation of the server side of Google Cloud Messaging">See Google's documentation for details</a>.</p>
<p>The <code class="preserve-code-formatting">delay_while_idle</code> attribute tells Google that it should not send a message when the client device is not active. A value of <code class="preserve-code-formatting">true</code> means that messages are kept on Google's server until the device is active again.</p>
<p>The <code class="preserve-code-formatting">collapse_key</code> probably needs some more explanation. If a device is offline you do not want it to get swamped with messages when it goes online again. Instead you can use the attribute <code class="preserve-code-formatting">collapse_key</code> to ensure that only the last message for this key gets delivered to the app. But note: You can use only four collapse keys at the same time. The <code class="preserve-code-formatting">collapse_key</code> applies to messages not delivered right away because of an <code class="preserve-code-formatting">delay_while_idle</code> flag, but also to messages than cannot be delivered because the device isn't connected at all.</p>
<p>You might have noticed that the <code class="preserve-code-formatting">data</code> attribute is optional. Now at first this might sound like a pointless exercise. Why send a message without any data in it? But it depends on the purpose of the message. You can use a GCM message as a tickle. To simply notify your app, that there's new data on the server to download. Unless the app can download different types of data, an empty message would be enough. When such a message arrives, your app would try to contact your server and download what it has to know.</p>
<p>If you do not set a <code class="preserve-code-formatting">time_to_live</code> value, the default is used. The default currently is four weeks.</p>
<h3>Message acknowledgements</h3>
<p>The GCM Cloud Connection Server expects your server to acknowledge each and every method it sends to you. Google states explicitly that you should never send a NACK!</p>
<p>Always having to acknowledge messages means you should be able to deal with those messages. Take care of exceptional conditions, that might come up at your end. Google will resend messages for which you fail to send an acknowledgement. So not acknowledging puts unnecessary burden on your server.</p>
<p>Here's what Google expects your server to adhere to:</p>
<blockquote>
<p>
For each device message your app server receives from CCS, it needs to send an ACK message. It never needs to send a NACK message. If you don't send an ACK for a message, CCS will just resend it.</p>
<p style="font-size: 0.8em;text-align: right">Source: <a href="https://developer.android.com/google/gcm/ccs.html#format" title="Documentation of GCM message formats"></a>https://developer.android.com/google/gcm/ccs.html</p>
</blockquote>
<p>Google sends back ACK or NACK messages for every message your backend sends towards Google's cloud. Google obviously is allowed to send NACKs. A NACK coming from Google means that you did something wrong - most of the time at least. For example you will get NACK messages for trying to send messages to registration ids that aren't valid anymore.</p>
<p>Google will also send NACKs if the service is down or in case an "Internal Server Error" occurred. In the first case you should simply queue the message to resend it sometime later. In the second case though, you are a bit on your own. Most likely resending should be fine since most other cases are handled with other exception codes. So most likely it's a problem on Google's end - but you cannot know for sure. Maybe the problem is caused by the content of your message after all. It might be a good idea to add an internal retry counter which you decrease with every transmission. At the very least log those cases and have a look at them.</p>
<h3>Receive messages from Google's cloud</h3>
<p>To handle incoming messages with Smack, you first have to register a <a href="http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/index.html?org/jivesoftware/smack/PacketListener.html" title="Documentation of Smack's PacketListener">PacketListener</a> object with the Connection you created in the first step above. This object is responsible for all incoming traffic. See this slightly adapted version of <a href="http://developer.android.com/google/gcm/ccs.html#smack" title="The original CcsClient code from Google's CCS page">Google's code</a>:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
connection.addPacketListener(new PacketListener() {
   @Override
   public void processPacket(Packet packet) {
      Message incomingMessage = (Message) packet;
      GcmPacketExtension gcmPacket =
            (GcmPacketExtension)incomingMessage
                  .getExtension(GCM_NAMESPACE);
      String json = gcmPacket.getJson();
      try {
         Map jsonMap =
               (Map)JSONValue.parseWithException(json);
         
         handleMessage(jsonMap);
      } catch (ParseException e) {
         logger.log(Level.SEVERE, &quot;Error parsing JSON &quot; + json, e);
      } catch (Exception e) {
         logger.log(Level.SEVERE, &quot;Couldn't send echo.&quot;, e);
      }
   }
}, new PacketTypeFilter(Message.class));</code></pre>
</div>
<p>And <code class="preserve-code-formatting">handleMessage()</code> looks like this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
private void handleMessage(Map&lt;String, Object&gt; jsonMap) {
   // only present for &quot;ack&quot;/&quot;nack&quot; messages
   Object messageType = jsonMap.get(&quot;message_type&quot;);
   if (messageType == null) {
      // Normal upstream data message
      CcsMessage msg = getMessage(jsonMap);
      handleIncomingDataMessage(msg);
      // Send ACK to CCS
      String ack = createJsonAck(msg.getFrom(), msg.getMessageId());
      send(ack);
   } else if (&quot;ack&quot;.equals(messageType.toString())) {
      // Process Ack
      handleAckReceipt(jsonMap);
   } else if (&quot;nack&quot;.equals(messageType.toString())) {
      // Process Nack
      handleNackReceipt(jsonMap);
   } else {
      logger.log(Level.WARNING, &quot;Unrecognized message type (%s)&quot;,
      messageType.toString());
   }
}</code></pre>
</div>
<p>The <code class="preserve-code-formatting">PacketListener</code> has just one method: <code class="preserve-code-formatting">processPackage()</code> which takes a <a href="http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/index.html?org/jivesoftware/smack/packet/Packet.html" title="Documentation of Smack's Packet object">Packet</a> as argument.</p>
<p>A data package - that is an upstream message coming from a device - is then delegated to <code class="preserve-code-formatting">handleIncomingDataMessage()</code>. For my sample project I have modified Google's original code quite a bit. For one I use a <a href="https://github.com/writtmeyer/gcm_server/blob/master/src/com/grokkingandroid/sampleapp/samples/gcm/ccs/server/CcsMessage.java" title="Source code of the sample's CcsMessage class">CcsMessage</a> object here that represents the incoming message.</p>
<p>Next I use <a href="https://github.com/writtmeyer/gcm_server/blob/master/src/com/grokkingandroid/sampleapp/samples/gcm/ccs/server/PayloadProcessor.java" title="The source of the PayloadProcessor interface">PayloadProcessors</a> to deal with the different type of messages. For every possible type of message I have a specific implementation of this interface to actually deal with the incoming message. You can of course replace this logic with whatever suits you.</p>
<p>What you do within those <code class="preserve-code-formatting">PayloadProcessors</code> is very app-specific. The sample code just provides very basic implementations to give you an understanding of how to deal with messages. Hopefully your app has more to offer than my sample <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Send messages to Google's cloud</h3>
<p>To send a message to Google's Cloud Connection Server, you have to follow these steps:</p>
<ol>
<li>Create the JSON payload</li>
<li>Create a Smack <code class="preserve-code-formatting">Packet</code> for the message</li>
<li>Send the XML message to Google's cloud</li>
</ol>
<h4>Create the JSON payload</h4>
<p>With json-simple you can create a JSON object from is a map by calling <code class="preserve-code-formatting">JSONValue.toJSONString()</code>. Each key of the map corresponds to one JSON attribute. In the section about message types I have listed the possible attributes. With this you can first create the map:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public static Map createAttributeMap(
      String to, 
      String messageId, 
      Map&lt;String, String&gt; payload,
      String collapseKey, 
      Long timeToLive, 
      Boolean delayWhileIdle) {
   Map&lt;String, Object&gt; message =
         new HashMap&lt;String, Object&gt;();
   if (to != null) {
      message.put(&quot;to&quot;, to);
   }
   if (collapseKey != null) {
      message.put(&quot;collapse_key&quot;, collapseKey);
   }
   if (timeToLive != null) {
      message.put(&quot;time_to_live&quot;, timeToLive);
   }
   if (delayWhileIdle != null &amp;&amp; delayWhileIdle) {
      message.put(&quot;delay_while_idle&quot;, true);
   }
   if (messageId != null) {
      message.put(&quot;message_id&quot;, messageId);
   }
   message.put(&quot;data&quot;, payload);
   return message;
}</code></pre>
</div>
<p>Using this method creating a JSON string for sending a message is simple:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public static String createJsonMessage(
      String to, 
      String messageId, 
      Map&lt;String, String&gt; payload,
      String collapseKey, 
      Long timeToLive, 
      Boolean delayWhileIdle) {
   return createJsonMessage(
         createAttributeMap(
               to, 
               messageId, 
               payload,
               collapseKey, 
               timeToLive, 
               delayWhileIdle));
}

public static String createJsonMessage(Map map) {
   return JSONValue.toJSONString(map);
}</code></pre>
</div>
<h4>Create a Smack Packet for the message</h4>
<p>Creating a <code class="preserve-code-formatting">Packet</code> object is even simpler. Google's code makes use of the extension mechanism of Smack. Smack's extensions are handlers for specific message types. The code uses them for processing incoming as well as outgoing messages.</p>
<p>Google's inner class <code class="preserve-code-formatting">GcmPacketExtension</code> is an implementation of Smack's <a href="http://www.igniterealtime.org/builds/smack/docs/latest/javadoc/index.html?org/jivesoftware/smack/packet/PacketExtension.html" title="Documentation of Smack's PacketExtension interface">PacketExtension</a> interface.</p>
<p>It's method <code class="preserve-code-formatting">toPacket()</code> creates an XML Packet, in this case it wraps the JSON with appropriate XML as required by XMPP.</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
Packet request = new GcmPacketExtension(jsonRequest).toPacket();</code></pre>
</div>
<h4>Send the message to Google's cloud</h4>
<p>If you have a <code class="preserve-code-formatting">Packet</code> object you simply call <code class="preserve-code-formatting">send()</code> on your <code class="preserve-code-formatting">XMPPConnection</code> object that you created connecting to Google's server in step one.</p>
<p>My demo follows Google's sample code in combining the last two steps in the method <code class="preserve-code-formatting">send()</code> of the <code class="preserve-code-formatting">CcsClient</code> class:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public void send(String jsonRequest) {
   Packet request = new GcmPacketExtension(jsonRequest).toPacket();
   connection.sendPacket(request);
}</code></pre>
</div>
<h3>Sending to multiple recipients via Google's Cloud Connection Server</h3>
<p>You cannot send a message to multiple recipients when using Google's Cloud Connection Server. Instead you have to send one message for every registration id you want to send a message to. That's why I added the message <code class="preserve-code-formatting">sendBroadcast()</code> which simply iterates over all recipients:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
public void sendBroadcast(Map&lt;String, String&gt; payload, String collapseKey,
      long timeToLive, Boolean delayWhileIdle, List&lt;String&gt; recipients) {
   Map map = 
         createAttributeMap(null, null, payload, 
         collapseKey, timeToLive, delayWhileIdle);
   for (String toRegId: recipients) {
      String messageId = getRandomMessageId();
      map.put(&quot;message_id&quot;, messageId);
      map.put(&quot;to&quot;, toRegId);
      String jsonRequest = createJsonMessage(map);
      send(jsonRequest);
   }
}</code></pre>
</div>
<p><strong>Note:</strong> There actually <em>is</em> one option to target multitple registrations ids with just one message. With user specific messages you can target all devices of one user. But you're still limited to one user only with this option. Since I'm going to cover user specific messages in my next post, I won't deal with this option here.</p>
<h3>You can combine HTTP and XMPP</h3>
<p>Google allows you to use HTTP at the same time as XMPP to send messages to devices. It's up to you if you want to use XMPP just to receive upstream messages of devices and to acknowledge those messages or if you want to use XMPP to talk to Google's Cloud Connection Server (CCS) for everything.</p>
<p>Actually there is one use case for which you <em>have</em> to use HTTP - at least at the moment. I very much hope that this will change when the final version of those new services is released for everyone. I will cover that specific use case next week.</p>
<h3>One final thing</h3>
<p>I have written most of the server code in preparation of my talk at the <a href="http://www.dutchaug.org/" title="Website of the Dutch Android User Group">Dutch Android User Group</a> meetup. As I have written in <a href="http://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/" title="Post about Google Cloud Messaging mentioning the signup procedure">my previous post about Google Cloud Messaging</a>, you have to <a href="https://services.google.com/fb/forms/gcm/" title="Link to the signup form for Google Cloud Messaging's new features">sign up to use the new features</a> like upstream messaging, XMPP or user notifications. After signing up, Google processes your request and some time later comes back with the approval. In my case the approval took a while and the preparation for the talk was in jeopardy. </p>
<p>Gladly <a href="https://plus.google.com/113269803670398336067" title="Dennis geurts' Google Plus profile page">Dennis Geurts</a> offered to use his testing API key and project id for which he had signed up much earlier. A big thanks for that, Dennis!</p>
<h3>Lessons learned</h3>
<p>With this post I have shown you some aspects of the server side of Google Cloud Messaging using the new upstream messaging model.</p>
<p>You have seen the different message types, have heard of the need to acknowledge messages and how to receive and send messages using Smack's Java library for XMPP. Since XMPP is text based those code snippets should be easy to transform to any other language.</p>
<p>Together with the source of the demo project this post should get you on the right track to set up your own project.</p>
<p>If you want to start using Google Cloud Messaging, be sure to read the official documentation. I couldn't cover all in this post. Be sure to not forget the <a href="https://developer.android.com/google/gcm/adv.html" title="Google's page for advanced Google Cloud Messaging topics">document about advanced topics</a>. There is also a nice blog post by <a href="https://plus.google.com/+RyanOldenburg" title="Ryan Oldenburg's Google Plus profile page">Ryan Oldenburg</a> of <a href="http://www.pushbullet.com" title="Pushbullet's home page">Pushbullet</a> about <a href="http://blog.pushbullet.com/2014/02/12/keeping-google-cloud-messaging-for-android-working-reliably-techincal-post/" title="Pushbullet's blog post stuff to take care of when using Google Cloud Messaging">some thinks to keep in mind when using GCM</a>. It might help you to avoid problems right away. For another perspective on the topic you might also want to read Antoine Campbell's <a href="https://www.captechconsulting.com/blog/antoine-campbell/google-cloud-messaging-cloud-connection-server-tutorial" title="Antoine Campbell on Cloud Connection Server">Cloud Connection Server Tutorial</a>.</p>
<p>One final problem: Right now I don't know any SaaS or BaaS provider to support the XMPP messaging model for Google Cloud Messaging. This is a serious limitation in my opinion - one which I expect to get much better when this model gets adopted more often and is published to all without approval process. Should you know of any provider supporting the new GCM model, please drop me a line.</p>
<p>The post <a href="https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/">An XMPP Server for Google Cloud Messaging</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/feed/</wfw:commentRss>
			<slash:comments>104</slash:comments>
		
		
			</item>
		<item>
		<title>Upstream Messages With Google Cloud Messaging</title>
		<link>https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/</link>
					<comments>https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 06 Feb 2014 08:39:14 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CCS]]></category>
		<category><![CDATA[Cloud Connection Server]]></category>
		<category><![CDATA[Google Cloud Messaging]]></category>
		<category><![CDATA[Upstream Messaging]]></category>
		<category><![CDATA[User notifications]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2797</guid>

					<description><![CDATA[<p>Google announced a new messaging model with Google Cloud Messaging on last years Google IO. This model allows for upstream messaging and for user specific notifications. This post is the first in a three-part series in which I am going to look into both these changes and to show you how to use them. I [...]&#160;&#160;<a href="https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/">Continue Reading&#160;&#160;"Upstream Messages With Google Cloud Messaging"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/">Upstream Messages With Google Cloud Messaging</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Google announced a new messaging model with Google Cloud Messaging on last years Google IO. This model allows for upstream messaging and for user specific notifications. This post is the first in a three-part series in which I am going to look into both these changes and to show you how to use them.</p>
<p>I had never written these posts if it weren't for the <a href="http://dutchaug.org" title="The website of the Dutch Android User Group">Dutch Android User Group</a> meetup in Utrecht (January 2014), where I had the pleasure to talk about this topic. This event was well-attended and was packed with <a href="http://www.meetup.com/dutch-aug/events/154627662/" title="List of talks of the DAUG meetup, January 2014">interesting talks about the changes in Android 4.4 and Google Play Services</a>. If you have ever the chance to attend a meetup of our Dutch colleagues, I strongly suggest to do so. It has been a gorgeous evening and was well worth the two-hour drive. It was not just the talks but also the overall atmosphere as well as the conversations during the breaks and afterwards. A big thanks to the organizers for the awesome evening! </p>
<p>You can find my <a href="https://speakerdeck.com/writtmeyer/google-cloud-messaging-with-ccs-and-xmpp" title="Slides for my talk about GCM at the DAUG meeting">slides on the speakerdeck site</a>. And a video of the talk should also be available pretty soon.</p>
<h3>Sample App</h3>
<p>I have published sample apps on github where you can see how to use this in context. For the Android client clone the <a href="https://github.com/writtmeyer/gcm_sample" title="Github page of the Android sample project for GCM upstream messaging">gcm_sample project</a>. For the server clone the <a href="https://github.com/writtmeyer/gcm_server" title="Github page of the sample project for the server side of GCM upstream messaging">gcm_server project</a>.</p>
<h3>What's new</h3>
<p>With Google Play Services 3.1 <a href="http://android-developers.blogspot.de/2013/05/social-gaming-location-and-more-in.html" title="Blogposts announcing changes to Google Play Services with 3.1">Google made some changes to Google Cloud Messaging</a>:</p>
<ul>
<li>You can send messages upstream from the user's device</li>
<li>You have to use a permanent connection between your backend and Google's services</li>
<li>You can use user specific notifications</li>
</ul>
<p>In this post I will only cover upstream messaging. That is the flow of events and what to do on Android's side. <a href="http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/" title="An XMPP Server for Google Cloud Messaging">In my next post I'm going to cover the server side</a> - and in the third post I will write about user specific notifications. User notifications allow you to send user specific messages with the possibility to cancel notifications on other devices if they have been consumed already on one device.</p>
<h3>Upstream messaging</h3>
<p>With the new GCM release Google allows you to send messages directly back to Google's cloud. That's what they call upstream messaging. Have a look at the following diagrams. The first one is the traditional model of Google Cloud Messaging while the second one shows the new flow of events.</p>
<figure id="attachment_2810" aria-describedby="caption-attachment-2810" style="width: 300px" class="wp-caption alignleft"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_classic.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_classic-300x242.png" alt="The classic communication flow with Google Cloud messaging" width="300" height="242" class="size-medium wp-image-2810" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_classic-300x242.png 300w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_classic.png 900w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2810" class="wp-caption-text">The classic communication flow with Google Cloud messaging</figcaption></figure>
<figure id="attachment_2835" aria-describedby="caption-attachment-2835" style="width: 300px" class="wp-caption alignleft"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs-300x242.png" alt="The communication model of Google Cloud Messaging with the new Cloud Connection Server" width="300" height="242" class="size-medium wp-image-2835" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs-300x242.png 300w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/02/gcm_ccs.png 900w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2835" class="wp-caption-text">The communication model of Google Cloud Messaging with the new Cloud Connection Server</figcaption></figure>
<p class="clear">
The first two steps in both diagrams are the same: You tell the Google Cloud Messaging API that you want to register a device (step 1). If the registration succeeds Google returns the registration id for this device (step 2).</p>
<p>Traditionally you would then send the registration id back to your server (step 3). The protocol was up to you but very likely HTTP. The server would (hopefully) respond with a success message (step 4).</p>
<p>From then on your server could send messages to Google's Cloud Messaging service (step 5) and the user's device would receive it, if it's registration id was part of the <code class="preserve-code-formatting">registration_ids</code> parameter of the message (step 6).</p>
<p>With upstream messaging though your app would send the registration id (step 3) not directly to your server, but instead call a method of the Google Play Services API. Google Play Services would then send the message to Google's servers.</p>
<p>Google then processes the message and sends it to your backend. Obviously for this to work your backend must be connected in some way to Google's cloud. <a href="http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/" title="An XMPP Server for Google Cloud Messaging">I will deal with this part in my next post</a>. For now it's enough to know that there has to be a permanent connection between your backend and Google's cloud and that Google will deliver messages that way (step 4).</p>
<p>After the registration id has been transmitted successfully you can send messages to the device (step 5). But with the new way to use Google Cloud Messaging you would use the existing connection between your server and Google's servers and use a different protocol (with slightly different parameters).</p>
<p>Note that Google uses different names for its servers depending on which transmission model you want to use. Google uses the name "<strong>GCM HTTP Connection Server</strong>" for those servers receiving HTTP messages and it uses "<strong>GCM Cloud Connection Server</strong>" for those receiving XMPP messages via the permanent connection. The abbreviation CCS is very commonly used within <a href="https://developer.android.com/google/gcm/index.html" title="Starting page for the GCM documentation">GCM's documentation</a>.</p>
<h3>Create your credentials</h3>
<p>If you already use Google Cloud Messaging you can skip this part and proceed to the next section.</p>
<p>If you're new to Google Cloud Messaging, you have to create an API key in Google's Cloud Console/Google Developer Console. Do not confuse it with the Google Play Developer Console. Both are unrelated.</p>
<p>After logging in to the Cloud Console you will see a list of projects. Simply create a new one and give it a name and a project id in the next dialog. Now this could be a source of confusion. <strong>The project id you use here is not the project id you have to use in your code later on.</strong> It's just a name which nevertheless has to be unique.</p>
<p>Afterwards creating the project the developer console will show you the project's page. Go to "APIs &amp; Auth" in the menu and turn on "Google Cloud Messaging for Android" in the huge list of Google's services. Since Google displays all your active services at the top, the entry will move directly to the top after you enable it. Don't be irritated by that tiny UX glitch. Simply scroll to the top and you will see that it's status has changed to "On". That's great.</p>
<p>Switch to Credentials in the menu on the left. At the top of the new screen you can find a client id. It starts with a number followed by ".apps.googleusercontent.com". Select the number (only the number), copy it and paste it into your <code class="preserve-code-formatting">strings.xml</code> - or a special <code class="preserve-code-formatting">gcm_strings.xml</code> that only contains the project id. Name the string whatever you like - in the <a href="https://github.com/writtmeyer/gcm_sample" title="The sample project for the GCM Android client">sample project</a> I expect a string named <code class="preserve-code-formatting">gcm_project_id</code>.</p>
<p>That's all you need for the Android part. But since you're logged in to the dev console anyway, let me show you how to create the API key for your server right away.</p>
<p>Go back to the dev console. On the Credentials page there are two sections. The OAuth section on the top is where you have found the project id. Below of it is the section called "Public API access". It's still empty. Click "Create New Key" and in the next dialog select "Server key". Afterwards you will see the API key for server applications together with some additional information. You will use the API key when following my <a href="http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/" title="An XMPP Server for Google Cloud Messaging">post about the server side of GCM</a>.</p>
<h3>Sign up for using the new features</h3>
<p>To be able to use all the shiny new features of Google Cloud Messaging, you have to sign up first. With the <a href="https://services.google.com/fb/forms/gcm/" title="Sign up form for the new features of Google Cloud Messaging">sign up form</a> you "Sign up to be a trial partner". The new services are not yet finalized. It's a bit like it has been with Google Cloud to Device Messaging (C2DM) - the predecessor to GCM. You had to sign up as well, and when the service was finally made public, it had evolved to Google Cloud Messaging. So expect the API to change!</p>
<h3>Using Google Play Services</h3>
<p>You need to use Google Play Services from within your app for registering the device for as well as for sending upstream messages.</p>
<p>Setting up Google Play Services is easy, but requires too many steps to cover them in this post. And those steps also are different depending on whether you use Android Studio, Eclipse or something else. Have a look at the <a href="http://developer.android.com/google/play-services/setup.html" title="Documentation on how to set up Google Play Services">Play services documentation</a> if it's the first time you use Google Play Services.</p>
<p>The very first step in your code when using Google Play Services is to make sure that Google Play Services are available at all. You can do so with the following snippet:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
private boolean checkPlayServices() {
   int resultCode = 
         GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(getActivity());
   if (resultCode != ConnectionResult.SUCCESS) {
      if (GooglePlayServicesUtil.
            isUserRecoverableError(resultCode)) {
         GooglePlayServicesUtil.getErrorDialog(
               resultCode, 
               getActivity(),
               RC_RES_REQUEST).show();
      } else {
         Log.i(&quot;grokkingandroid&quot;, 
               &quot;This device is not supported.&quot;);
      }
      return false;
   }
   return true;
}</code></pre>
</div>
<p>What to do when the services are not available, depends on how important they are for your app. If Play Services are not essential, I suggest to let the user know - but in an unobtrusive way. After all the app is usable without it, so do not annoy your users with dialogs or other stuff that keeps them from doing what they actually installed the app for.</p>
<h3>Registering the device for Google Cloud Messaging</h3>
<p>The next step is to register the device. Google needs to know about your device before your app is allowed to receive or send messages.</p>
<p>In my sample app the user has to explicitly click the button register. Not a typical use case, but for the sample this makes sense. Now when to do this is in a real app is up to you. But when your app benefits from Google Cloud Messaging you usually want to register the device as soon as possible. </p>
<p>I also let the user select a Google account. Your app's users do not need one for Google Cloud Messaging. I solely request one to use this account for user specific notifications. I will cover those in the third post of this series.</p>
<p>Registering actually is very easy. First get hold of a <code class="preserve-code-formatting">GoogleCloudMessaging</code> object and then simply call its method <code class="preserve-code-formatting">register()</code> passing in the project id of the dev console (see "Create your credentials" above):</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
String projectId = 
      getResources().getString(R.string.gcm_project_id);
GoogleCloudMessaging gcm = 
      GoogleCloudMessaging.getInstance(this);
String regid = gcm.register(projectId);</code></pre>
</div>
<p>Be careful though: Asking for the registration id is a blocking request. Hence, you should always use the call in a separate thread off the main thread (UI thread). In the sample project I am using an IntentService to achieve this.</p>
<h3>Send messages upstream</h3>
<p>As soon as the device is registered, it can send messages upstream - as well as receive messages. Probably the very first message to send upstream is the newly received registration id.</p>
<p>Sending messages is nearly as simple as registering. You create a <code class="preserve-code-formatting">Bundle</code> with all the payload data you want to transmit and you also have to create a unique message id. In my sample code I simply increase a counter I keep within the <code class="preserve-code-formatting">SharedPreferences</code> for the message id. Depending on your payload the code might look more or less like this:</p>
<div class="sourcecode">
<pre class="language-java line-numbers" data-line="10,11"><code class="language-java line-numbers">
try {
   Bundle data = new Bundle();
   // the account is used for keeping 
   // track of user notifications
   data.putString(&quot;account&quot;, account);
   // the action is used to distinguish 
   // different message types on the server
   data.putString(&quot;action&quot;, Constants.ACTION_REGISTER);
   String msgId = Integer.toString(getNextMsgId());
   gcm.send(projectId + &quot;@gcm.googleapis.com&quot;, msgId,
         Constants.GCM_DEFAULT_TTL, data);
} catch (IOException e) {
   Log.e(&quot;grokkingandroid&quot;,
         &quot;IOException while sending registration id&quot;, e);
}</code></pre>
</div>
<p>As you can see you once again need a <code class="preserve-code-formatting">GoogleClientMessaging</code> object and call its <code class="preserve-code-formatting">send()</code> message.</p>
<p>This message takes as parameters the project id appended with the fixed string "<code class="preserve-code-formatting">@gcm.googleapis.com</code>", a unique message id, a time to live value and the bundle with your payload.</p>
<p>You might notice that I do not include the registration id as part of the payload. That's because Google Play Services adds the registration id to every message to your backend anyway. You will see in the next post which parameter Google uses for the registration id. For now, just keep in mind that above code is all that is actually needed. </p>
<p>Those strings within the bundle are not even necessary. I use the <code class="preserve-code-formatting">account</code> because I want to send user specific messages and I use the <code class="preserve-code-formatting">action</code> to differentiate on my server between different message types.</p>
<p>As you can see there is no special message for sending the registration id back home. It's just a message like any other upstream message.</p>
<h3>Benefits of Upstream messaging</h3>
<p>Now that you know <em>how</em> to send upstream messages, you might wonder about <em>why</em> to use upstream messaging in the first place. Why not send your message back to your server as you always did (assuming you <em>did</em> contact your server)?</p>
<p>There are three reasons on the Android side for using the new model:</p>
<ul>
<li>The upstream messaging API is dead simple</li>
<li>Upstream messages can reuse connections</li>
<li>Upstream messages are needed for notification cancellation</li>
</ul>
<h4>The API is dead simple</h4>
<p>You have seen how simple the Android code is. It's just some message calls to Google Play Services's <a href="https://developer.android.com/reference/com/google/android/gms/gcm/GoogleCloudMessaging.html" title="API of the class GoogleCloudMessaging">GoogleCloudMessaging</a> class. It's really just this one class, which with only six public methods is not too difficult to grasp <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
<p>Contrast that with using HTTP instead: When talking back to your own servers directly you have to take care of checking if the network is available, send off the message, check for any error conditions and enqueue the message for later delivery if anything goes awry. All in all you're better of with upstream messaging - at least for as long as you only care about the Android code.</p>
<h4>Upstream messages can reuse connections</h4>
<p>Not only is the API easier to use, it can also save resources. The user's device has a connection to Google anyway so with upstream messaging Google Play Services can reuse this connection. The services take care of using the most power efficient way to send messages so you do not have to deal with that. This helps keeping the battery usage of your app to a minimum. </p>
<p>Of course if your app only sends messages every once in a while, your users won't notice any change in the battery usage. But if your app has to send many messages to your backend, this might make a difference to your users.</p>
<h4>Upstream messages are needed for notification cancellation</h4>
<p>The strongest argument for using upstream messaging though is notification cancellation. If you send messages from your server to specific users, you do not want them to see a notification on each and every device - even if it has long been read on another device. I will deal with user specific messages and notification cancellation in my third post about Google Cloud Messaging. So stay tuned <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h3>Permissions</h3>
<p>To use Google Cloud Messaging you need quite a lot of permissions:</p>
<div class="sourcecode">
<pre class="language-markup line-numbers"><code class="language-markup line-numbers">
&lt;uses-permission 
   android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;uses-permission 
   android:name=&quot;android.permission.GET_ACCOUNTS&quot; /&gt;
&lt;uses-permission 
   android:name=&quot;android.permission.WAKE_LOCK&quot; /&gt;
&lt;uses-permission 
   android:name=&quot;com.google.android.c2dm.permission.RECEIVE&quot; /&gt;
&lt;permission 
   android:name=
      &quot;com.grokkingandroid.sampleapp.samples.notifications.gcm.permission.C2D_MESSAGE&quot;
   android:protectionLevel=&quot;signature&quot; /&gt;
&lt;uses-permission 
   android:name=
      &quot;com.grokkingandroid.sampleapp.samples.notifications.gcm.permission.C2D_MESSAGE&quot; /&gt;</code></pre>
</div>
<p>The first three are predefined permissions. You might notice the account permission. Actually this one is only needed for API levels before Android 4.0.4. I added it for completeness. </p>
<p>The fourth is a bit of an oddity. It's the old Cloud to Device Messaging (C2DM) permission. For backwards compatibility it makes sense to not change it - otherwise existing apps had to ask for a new permission. But it looks weird about two years after C2DM was deprecated.</p>
<p>You also have to create a new permission of your own. That's the permission that ensures that no other app can receive messages intended for your app. It has to exactly follow this naming convention: Package name plus "<code class="preserve-code-formatting">.permission.C2D_MESSAGE</code>". Otherwise your app won't receive the messages sent to it. Your app also must use this newly created permission.</p>
<h3>Receiving messages</h3>
<p>Of course the fun part of Google Cloud Messaging is to actually <em>receive</em> push messages from the cloud. Google transmits the messages to your app to a <code class="preserve-code-formatting">BroadcastReceiver</code>. </p>
<p>The following code is basically the same as <a href="https://developer.android.com/google/gcm/client.html" title="Google's documentation for the client side of Google Cloud Messaging">Google's sample code on their client page</a>:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
/**
 * See http://developer.android.com/google/gcm/client.html
 */
public class GcmBroadcastReceiver 
      extends WakefulBroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      // Explicitly specify that
      // GcmIntentService will handle the intent.
      ComponentName comp = 
            new ComponentName(
               context.getPackageName(),
               GcmIntentService.class.getName());
      // Start the service, keeping the 
      // device awake while it is launching.
      startWakefulService(
            context, 
            (intent.setComponent(comp)));
      setResultCode(Activity.RESULT_OK);
   }
}</code></pre>
</div>
<p>The Broadcastreceiver gets the message - but since it runs on the UI thread it should immediately pass the message on to some background thread. I use the same <code class="preserve-code-formatting">IntentService</code> you have already seen for registering the device.</p>
<p>Actually parsing the message and doing what has to be done is done in the service. Again The code is pretty much the same as on Google's documentation:</p>
<div class="sourcecode">
<pre class="language-java line-numbers"><code class="language-java line-numbers">
// handling of stuff as described on
// http://developer.android.com/google/gcm/client.html
try {
   Bundle extras = intent.getExtras();
   // The getMessageType() intent parameter
   // must be the intent you
   // received in your BroadcastReceiver.
   String messageType = gcm.getMessageType(intent);
   
   if (extras != null &amp;&amp; !extras.isEmpty()) {
      /*
      * Filter messages based on message type. 
      * Since it is likely that GCM will be 
      * extended in the future with new 
      * message types, just ignore any message 
      * types you're not interested in, or that you
      * don't recognize.
      */
      if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
            .equals(messageType)) {
         sendNotification(
            &quot;Send error: &quot; + extras.toString());
      } 
      else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
            .equals(messageType)) {
         sendNotification(&quot;Deleted messages on server: &quot;
            + extras.toString());
      } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
            .equals(messageType)) {
         // Post notification of received message.
         String msg = extras.getString(&quot;message&quot;);
         if (TextUtils.isEmpty(msg)) {
            msg = &quot;empty message&quot;;
         }
         sendNotification(msg);
      }
   }
} finally {
   // Release the wake lock provided by the WakefulBroadcastReceiver.
   GcmBroadcastReceiver.completeWakefulIntent(intent);
}</code></pre>
</div>
<p>As you can see GCM uses different message types. the last one is the one actually containing a new messages. The first one informs you about errors when sending messages and the second tells you that messages have been deleted. If for example you display incoming messages with a notification you would have to cancel the notification in this case.</p>
<p>What to do when receiving an actual message is very specific to your app. The sample app simply displays a notification.</p>
<p>Do not forget to release the wake lock. That's the line within the <code class="preserve-code-formatting">finally</code> block. The <code class="preserve-code-formatting">finally</code> block ensure that this call will always be done - even if any exception has been thrown in the code within the <code class="preserve-code-formatting">try</code> block. Be sure to do it that way!</p>
<h3>Lessons learned</h3>
<p>In this post you have seen how the message flow has changed when using Google Cloud Messaging. With the previous model you had to contact your server directly from the device, now you only tell Google Play Services what to do with the new upstream messaging model. Google's services take care of actually delivering the message to your server.</p>
<p>You also have learned about how to set up the project in Google's developer console and that you have to sign in to use the new features. </p>
<p>Finally you have seen how easy the Android code actually is and what the benefits of upstream messages are.</p>
<p>In the next post you will learn more about the <a href="http://www.grokkingandroid.com/xmpp-server-google-cloud-messaging/" title="An XMPP Server for Google Cloud Messaging">server side of upstream messaging</a> - which is a tad more complex. And after that I'm going to show you how to use user notifications in the final post of this series.</p>
<p>The post <a href="https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/">Upstream Messages With Google Cloud Messaging</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/upstream_messages_with_google_cloud_messaging/feed/</wfw:commentRss>
			<slash:comments>44</slash:comments>
		
		
			</item>
		<item>
		<title>Chrome-Apps on mobile devices &#8211; a good idea?</title>
		<link>https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/</link>
					<comments>https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 30 Jan 2014 13:30:06 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Chrome apps]]></category>
		<category><![CDATA[Web apps]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2780</guid>

					<description><![CDATA[<p>Google announced a new set of tools this week to help developers publish their Chrome apps on iOS and Android. That's the next logical step by Google to win over more developers for Chrome apps. In September Google already announced that from then on developers could publish their Chrome apps as offline apps, allowing users [...]&#160;&#160;<a href="https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/">Continue Reading&#160;&#160;"Chrome-Apps on mobile devices &#8211; a good idea?"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/">Chrome-Apps on mobile devices &#8211; a good idea?</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Google announced a new set of tools this week to help developers publish their Chrome apps on iOS and Android. That's the next logical step by Google to win over more developers for Chrome apps. In September Google already announced that from then on developers could publish their Chrome apps as offline apps, allowing users to use them like any other desktop application. Those offline apps from now on can also be published on iOS and Android. BTW: It's interesting that Windows Phone is no target platform for Chrome apps and hasn't even been mentioned on the blog post.</p>
<p>To make this work, Chrome apps have to use a thin wrapper to be considered a "native" app and to access phone functions not available via HTML 5 as of yet. For this Google uses <a href="http://cordova.apache.org/" title="Project page of Apache Cordova">Apache Cordova</a>, better known as Phonegap. With the help of this project and further additions made by Google, Chrome apps can be published on Google Play and Apple's App Store. You can <a href="http://blog.chromium.org/2014/01/run-chrome-apps-on-mobile-using-apache.html" title="Google's announcement for mobile Chrome apps">read more about it on Google's blog post</a>.</p>
<p>Users cannot recognize those apps as Chrome apps in the respective app stores. They just show up as any other app. And that's where the problem starts.</p>
<p>Taking a web app, which works fine on a desktop, wrapping it with some tools and publishing it, that's just not enough. Those apps would fall short of users' expectations.</p>
<p>First of all those apps would look totally out of place. Just have a look at this screenshot of Google's blog post:</p>
<figure id="attachment_2782" aria-describedby="caption-attachment-2782" style="width: 300px" class="wp-caption alignnone"><a href="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/01/todos.png"><img loading="lazy" decoding="async" src="http://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/01/todos-300x163.png" alt="Screenshot of one of Google&#039;s sample apps" width="300" height="163" class="size-medium wp-image-2782" srcset="https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/01/todos-300x163.png 300w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/01/todos-1024x557.png 1024w, https://www.grokkingandroid.com/wordpress/wp-content/uploads/2014/01/todos.png 1199w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a><figcaption id="caption-attachment-2782" class="wp-caption-text">Screenshot of one of Google's sample apps</figcaption></figure>
<p>There's no action bar, those buttons look weird, the header is very unusual - it just doesn't fit. Of course you could get around most problems and make it look properly - but that would require some additional work. You would no longer just wrap an existing app, but start to provide platform specific deviations to achieve proper designs.</p>
<p>Secondly interaction patterns on the web, on desktop apps and on mobile apps are totally different. Consider the differences between iOS and Android alone. Tons of difference like navigation patterns, action placements, list treatment and so on. This problem is much worse and has much more influence on whether an app feels like a properly done app or not. And no cross-platform tool can help you with that. You will end up with multiple versions for all supported platforms anyway. Just consider the code. You probably <em>can</em> structure this in a way that is maintainable - but not if the main reason for taking this route was saving costs in the first place.</p>
<p>Third I wonder about the quality of the apps. This is a very personal fear based on my experience with Firefox OS apps. Those are very often normal desktop apps as well - which too often do not work on a mobile device. It might happen, that desktop app developers simply wrap up their app and do neither test properly nor know about those limitations. Of course those apps would get ratings that bad, that they wouldn't show up for most searches anyway. But Google is setting expectations for devs here - and those devs might be very disappointed down the road.</p>
<p>As you've seen there are plenty of issues with the user experience. But obviously technical issues exist as well.</p>
<p>It seems that it's not that easy from a technical point of view as Google makes us believe it is. Just <a href="https://github.com/GoogleChrome/chrome-app-samples#mobile-support" title="List of sample apps and how well they work on the respective mobile platforms">have a look at the sample apps</a>. Five (!) of those 17 apps do not run on Android <em>at all</em>. Another six only with limitations. Or put it another way: Only one third of those apps works properly on Android. For iOS it's about the same (though with different apps): Six apps don't work at all, another five only with limitations. <strong>Only two out of 17 apps work properly on both supported platforms!</strong> And this is about to help devs? This should be a proper way to develop cross-platform apps? Not at all!</p>
<p>The only thing that I am confident to work properly is the responsiveness of those apps. Web developers do that for years. They understand and grok responsiveness.</p>
<p>If you want to publish apps and want your users to like your apps, you have to take the patterns and specifics of each platform into consideration. That means work. No matter which approach you choose. I guess that the total amount of work is even less if you design and develop different apps for Android, iOS, Windows Phone and (hopefully) Firefox OS than when you try to use a cross-platform tool. And I have yet to see a cross-platform app that actually <em>does</em> work properly on different platforms.</p>
<p>Google has done so much in recent years to consolidate the design, interaction patterns and overall usability of Android. Which makes the recent announcement all the more disappointing. It's a step backwards. It's going back to where we were some years ago: A world without a unified design language without common interaction patterns. I do not want this. And I strongly believe, users do not want this as well.</p>
<p>As a developer you have to keep an eye on this project. At least because your clients might mention it. But it's not working. At least not yet. If it ever will - I do not know.</p>
<p>Project managers and product managers should also carefully consider the limitations of this approach. Don't think it will save you money! Don't think it will save you time! If you're not careful and use it without proper analysis, you're bound to see costs rising unexpectantly (well, actually that's to be expected) and your users will still rate your app poorly.</p>
<p><strong>Note: This post has initially been written for the German publication computerwoche.de.</strong></p>
<p>The post <a href="https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/">Chrome-Apps on mobile devices &#8211; a good idea?</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/chrome-apps-mobile-devices-good-idea/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>FirefoxOS &#8211; my Initial Impression</title>
		<link>https://www.grokkingandroid.com/firefoxos-initial-impression/</link>
					<comments>https://www.grokkingandroid.com/firefoxos-initial-impression/#comments</comments>
		
		<dc:creator><![CDATA[Wolfram Rittmeyer]]></dc:creator>
		<pubDate>Thu, 19 Dec 2013 12:07:11 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[FirefoxOS]]></category>
		<guid isPermaLink="false">http://www.grokkingandroid.com/?p=2761</guid>

					<description><![CDATA[<p>Quite a while ago I ordered a Peak+ FirefoxOS phone at geeksphone.com. Alas after some delay it finally was cancelled - so I settled for the smaller version, the normal Peak. About a week or two ago it finally was delivered. After some very short initial testing I had more pressing things to do. But [...]&#160;&#160;<a href="https://www.grokkingandroid.com/firefoxos-initial-impression/">Continue Reading&#160;&#160;"FirefoxOS &#8211; my Initial Impression"</a></p>
<p>The post <a href="https://www.grokkingandroid.com/firefoxos-initial-impression/">FirefoxOS &#8211; my Initial Impression</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Quite a while ago I ordered a Peak+ FirefoxOS phone at <a href="http://www.geeksphone.com" title="The website of geeksphone.com">geeksphone.com</a>. Alas after some delay it finally was cancelled - so I settled for the smaller version, the normal Peak. About a week or two ago it finally was delivered. After some very short initial testing I had more pressing things to do. But this week I gave it another look. Here are my initial impressions - mostly of FirefoxOS and less of the Peak itself.</p>
<h3>The phone itself</h3>
<p>I was quite suprised by the size of the device. It's roughly the same as the N5 - though the screen is much smaller and the screen resolution even more so. That's not so good - but it's a dev phone, so it's not really that important. But for any handset maker out there: If your screen doesn't provide the resolutions current top devices spout, please make your device smaller.</p>
<p>Of course the phone is plastic all around - it's after all a cheap phone. I do not mind. I never thought, that plastic feels cheap. Actually I prefer plastic over metal or - even worse - glass. So it feels quite good - albeit a tiny bit too large. Some rubberized finish would be a nice addition, though.</p>
<p>The screen is surprisingly good. Of course the resolution is far away from those of top device, but mostly good enough. Only for screens with much text, the resolution is an issue. </p>
<p>The camera of course isn't great - but for simple snapshots it should be sufficient. You won't ever win a price with those pictures though.</p>
<p>Battery life: Seems to be good, very good indeed. But that's just an initial impression. I have yet to make the phone my primary device for a few days. Something I am not quite ready to do so, yet. You will see in the next section, why not. </p>
<h3>UX issues</h3>
<p>FirefoxOS is full of UX issues. I'm a developer and definitely no UX expert. But even I can spot many problems. Users will notice, will stumble upon those issues and think that something's not right. So in my opinion, Mozilla should concentrate on those issues - especially some stuff that from an outside perspective looks like something that should be easy to fix. Of course I know that this outside perspective is often misleading, but hopefully some issues <em>are</em> easy to fix. </p>
<p><strong>Touch feedback is rare.</strong> Which is a deadly sin for a touch based interface. Take the Action Bar (in FirefoxOS slang it's the Header). When I hit back in the top left corner, I want to see the back indicator highlighted. But that's not happening. So did I touch it? Should I touch again?  And it's not just in the FirefoxOS Header. </p>
<p>Missing touch feedback is sometimes made worse by a <strong>lacking loading indicator</strong>. I want to see a spinning wheel or some other indicator that content is loading - let me know that you do something. I hit back twice over and over because I had no feedback whatsoever. </p>
<p>Firefox Marketplace app lacks touch feedback as well as loading indicators all over the place. And the app doesn't seem to cache anything. It feels like the app reloads all lists whenever I go back to them. That slows things down considerably and make missing feedback even worse.</p>
<p>The next issue might partially be based on my Android experience. But whatever the reason: <strong>I miss the back button dearly.</strong> I'm not using "up" often on android and having to go up to the Header/Action Bar feels very weird. But it's not only uncomfortable, it's sometimes even problematic. What to do on with an information dialog? I happened to stumble upon that at least once. Granted, it's the fault of the app, but nevertheless a problem that could be hurting the OS adption.</p>
<p>The lock screen is also a UX fail. You first have to pull up a bar from the bottom - which is nicely indicated by an appropriate animation. But afterwards you have to do another step: You have to click on the unlock icon. <strong>Two steps to unlock the phone? That's one step too much.</strong> As simple as that!</p>
<p>The list of opened apps also has a problem. There's a button to close this app - which works more or less randomly. Swiping the app away, though, works fine all the time.</p>
<p>I had some trouble with flinging through lists. One problem: <strong>When flinging repeatedly in long lists, the flow stops.</strong> Don't know how to describe this correctly. But the new movement of my finger stops the last one and starts a new fling. That feels very unnatural. It doesn't feel like a continuing movement.</p>
<p>Another one is the notifications drawer. You have to drag it all the way down to see the top most notification. Which is bad if you just want to peek at the notification. It feels totally strange to have to scroll that far to <em>finally</em> see the one notification that caused you to use the notification drawer in the first place.</p>
<p>The on screen keyboard also feels kind of weird to me. Cannot exactly nail it, but it just doesn't feel right. Of course on Android I swipe most of the time, but it's not just that. The spacing between keys is very narrow, but I guess that isn't it either. Hopefully I can tell you in a follow-up post, what it is that actually bothers me. Right now it's just the feeling: This is not right. The only thinkg, I can tell you for sure, is the surprising location of the "'". It's right next to the letter "l" and directly above the return key. I accidentally hit it way too often.</p>
<h3>Apps</h3>
<p>The general quality of the app is not great - to say the least.</p>
<p>One example: Pulse as one of the top apps promoted in the news category. When starting Pulse for the first time, the first thing you see, is the suggestion to get the app! WTF! I do not <em>know</em> about the reason, but my guess is, that this Pulse "app" is simply the mobile website. Don't know if this is Pulse's fault or Mozilla's fault, but it sheds a bad light on the platform. This shouldn't happen. This mustn't happen!</p>
<p>Next I downloaded a Pomodoro timer and a kitchen timer. Neither of these works when the OS goes into sleep mode. What? A timer not ringing, when the screen turns off? These seem to be apps for a desktop firefox. If they do not work properly on FirefoxOS, those apps shouldn't be available in the marketplace on these devices. Some quality assurance must take care of that. I actually found not one timer app that deals with this correctly.</p>
<p>Another example is the stock Camera app. When taking a photo and viewing it from within the Camera app, I sometimes got a black screen when enlarging the picture. Initially I thought the app just crashed (or run into some endless loop), but all buttons were still visible and reacted properly. Actuall it's just that the screen remains black until the enlarged picture is ready to be displayed. Which can last an astonishingly long time. This is a horrible user experience - just show me some blown up but undetailed preview of the area and display more details progressively.</p>
<p>The Marketplace app itself has problems. I do not want to see <em>many</em> apps, I want to see <em>quality</em> apps. One timer would be enough if it works properly and has at least a decent usability. But about ten timers and none working as expected, that's about as useful as no timer at all. I also do not need all soccer leagues of the world. I want to find the one local to me (granted, some leagues might be more interesting to others worldwide than others, but I gues most people want to see the league of their home country). Same goes for news and anything else. I am still asztonished that Google doesn't provie a better search experience on Google Play, but now I can appreciate what they have been doing. Definitely the results are more relevant than thos in Firefox market place. </p>
<h3>Importing stuff</h3>
<p>As an Android user I obviously have stuff on Google's server. My contacts, my calendar, mail, what not. I was able to import contacts flawlessly, but strangely enough I couldn't import any calendar information. No error dialog, it simply stopped after I entered all credentials. This is crucial and could be a big issue for FirefoxOS.</p>
<p>And since we're at it: A central account setting makes life so much easier. That's something Android does very well. Not just for Google accounts, mind you. But for any apps that make use of sync adapters and authenticators. It's cumbersome to have to enter the credentials over and over again because there isn't such a central place in FirefoxOS.</p>
<h3>Initial verdict</h3>
<p>Boy, Mozilla has still a lot to do. I still very much hope for FirefoxOS to succeed. That's why I ordered the phone in the first place. I love Android but Android needs another viable <em>open</em> competitor. Microsoft and Apple obviously do not fit that description.</p>
<p>But to be competitive in the market place, there is still much to do for Mozilla and app devs developing for FirefoxOS. </p>
<p>Then Mozilla needs to adress the usability issues. There are probably many more I didn't even notice. But that's what makes users recommend a system if done right. If done wrong, though, users most probably will advise against buying it. Shouldn't happen.</p>
<p>And of course we <em>do</em> need more apps. For this FirefoxOS has to gain more traction. The usual catch-22 situation of all the follow-up systems in the mobile space. That's something we all can contribute to. If you want FirefoxOS to succeeed, help Mozilla out wth an app or two <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f642.png" alt="🙂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>Of course all is open source, so if you want to do so you can also help with all the other issues, I mentioned. Mozilla probably would be very happy about any new contributors to the platform.</p>
<p>This all sounds pretty dim. But you have to consider that it's only an initial impression. Then version 1.2 is in the making and might (hopefully) correct many of the issues. I personally still have hope for the platform. So much actually that I'm giving development for it a try and to publish an app myself. I will let you know about this in a future post. <strong>But:</strong> This is still an Android centric blog. FirefoxOS related posts will only be sparse in between.</p>
<p>Let me know what you think and what your experience with FirefoxOS has been.</p>
<p>The post <a href="https://www.grokkingandroid.com/firefoxos-initial-impression/">FirefoxOS &#8211; my Initial Impression</a> appeared first on <a href="https://www.grokkingandroid.com">Grokking Android</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.grokkingandroid.com/firefoxos-initial-impression/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced (Page is feed) 

Served from: grokkingandroid.com @ 2026-04-04 02:24:49 by W3 Total Cache
-->