<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[OrbisMobile - Medium]]></title>
        <description><![CDATA[Somos el grupo de desarrollo mobile del Grupo el Comercio - Medium]]></description>
        <link>https://medium.com/orbismobile?source=rss----5e49fab6609---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>OrbisMobile - Medium</title>
            <link>https://medium.com/orbismobile?source=rss----5e49fab6609---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 23:48:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/orbismobile" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Picking up specific information to your conversation | Entities in Dialogflow]]></title>
            <link>https://medium.com/orbismobile/picking-up-specific-information-to-your-conversation-entities-in-dialogflow-3353170f52a6?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/3353170f52a6</guid>
            <category><![CDATA[actions-on-google]]></category>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[google-actions]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Sun, 02 Sep 2018 05:32:15 GMT</pubDate>
            <atom:updated>2019-02-20T17:26:59.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*qmHF72KomHL24ABAMx9How.jpeg" /></figure><p>Imagine yourself talking to someone and at the end of the conversation she/he says: Sorry, I didn’t pay attention, I know you were talking to me but I forgot what you were talking about… What happens then? Conversation doesn’t flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*tZCV7bV69CVNAkdLflSwXQ.gif" /><figcaption>See how important it’s to pay attention?</figcaption></figure><p>It’s for this reason that it’s not only important to know that a conversation has started, it’s also important to collect important information from it, in order to generate alternative responses or flows when talking with our users.</p><p>And how can we collect information ?. Through <strong>Entities</strong> in Dialogflow. But what is an <em>Entity</em>?</p><p>They’re powerful tools used to extract required information from a natural conversation. Any important data you wish to obtain from the conversation must have its respective entity created. It’s not necessary to create entities for every possible word or phrase, only for the necessary data.</p><p>All right, enough talking and let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*iIsswMIJPkf-5g_hKDWRnA.gif" /></figure><h4>How do I use Entities?</h4><p>When we create an Intent, Dialogflow gives us the “Training phrases” section where we will put the entries that will activate the Intent for the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*aIN7i0hg5CA4e8cxzz3eWw.png" /><figcaption>Dialogflow Console — Intent</figcaption></figure><p>How do we use an Entity here? Well, let’s imagine we make an application for our bike shop (Yeah, I love bikes 😆) and one of the entrances is: My road bike is broken, can I go tomorrow?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*OzAHyhmYyHumJQ6t8UBRNw.png" /><figcaption>Example entrance — Dialogflow Console</figcaption></figure><p>Even this part is more than enough to activate the Intent, but we don’t collect data in any way. There are <em>two ways</em> to collect them (Example Mode &amp; Template Mode).</p><h4>Example Mode</h4><p>The <em>example mode</em> is activated by default in your “Training phrases”. In this mode, words that match your entities will be highlighted in color, and if they don’t match the first time, you can always double-click on the word or phrase you want to be recognized and choose the corresponding entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*oR1e-me3lU79ACDLVuv4xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*t8ysVta5QN3f1OIJBAwr8Q.png" /></figure><p>So far so good, but what if I need to validate more than one date? It would be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Isj84xNYyvjYnl4g-cUUcg.png" /><figcaption>No, I don’t think so, and there are still dates to go.</figcaption></figure><p>So what can we do, one option is to finish putting all the available dates on the calendar and then finish when we are old or . . .</p><h4>Template Mode</h4><p>To access this mode, we need to click on the icon on the left and see it change to a “@”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*07QjDFWri_44q2FbCO-R8Q.png" /><figcaption>Click on that icon.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*dDvp8I5HyMNhG1UkMbPtAg.png" /><figcaption>Perfect!</figcaption></figure><p>Then, instead of writing a lot of sentences about different dates, we can do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*BhpAAlbmKUCDSreX6niPAw.png" /></figure><p>As you can see, now instead of writing the matches, type the name of the entity (invoked by @) and then Dialogflow will match all the words and phrases of that entity.</p><p>Whichever mode you use to match the words, in both cases you need to define the <em>parameters</em> where you will store the data obtained by the entity.</p><h4>Parameters</h4><p>Through a parameter, we can connect a word or phrase to a specific entity. We can place them in two sections, <strong><em>“Training Phrases”</em></strong> section and <strong><em>“Action &amp; Parameters”</em></strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*H72Ww6bglAtZXEOYkllOlw.png" /><figcaption><strong><em>“Training Phrases”</em></strong> section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*jjfTLNeeL2B7tqlUhpP2DA.png" /><figcaption><strong><em>“Action &amp; Parameters”</em></strong> section</figcaption></figure><p>In both sections we observe that there are 3 equal fields: <em>Parameter Name, Entity and Value</em>.</p><ul><li><strong><em>Parameter Name: </em></strong>It’s the name given as a variable to take the matched value of the entity. It is very important to define them at the beginning, because if a value is not paired with a variable, the console will give them an error when trying to display a simulation. Normally the console automatically puts a name, but if you want you can change it, remember that the name is defined after the colon of the entity. You can change it from any section: <strong><em>“Training Phrases”</em></strong> section or <strong><em>“Action &amp; Parameters”</em></strong> section.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*hoJbwlWJtWprHGcr9NWpVw.png" /></figure><p>However, always remember to homogenize the names, having different names from the same entity could cause troubles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*5PPdrH7ivpml9RFpWhpTlg.png" /><figcaption>Please avoid this, believe me, you’ll thank me.</figcaption></figure><ul><li><strong><em>Entity</em></strong>: Name of the entity that matched. Dialogflow has three types of entities:</li></ul><pre><strong><em>System Entities</em></strong><br>Pre-built entities provided by Dialogflow that facilitate the most commonly used concepts in a conversation.</pre><pre><strong><em>Developer Entities</em></strong><br>If you need to recognize more specific or less common words or phrases in your conversation, you can create your own entity to match the data.</pre><pre><strong><em>User Entities</em></strong><br>Entities that can be defined for a specific user session. User entities and sessions last 30 minutes.</pre><ul><li><strong><em>Value: </em></strong>The <em>Value,</em> is the value obtained from the coincidence between a word or phrase and an entity. Note that in this section you must be very careful of the options that value can offer us, these are <strong><em>default</em></strong> and <strong><em>original</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*6JhjeXe0JiR5_0fmmo8GZA.png" /></figure><p>But, What is the difference between choosing a default and original value?. Let’s take the date as an example, if we ask something like: My road bike is broken, can I go tomorrow? Where <strong><em>“tomorrow”</em></strong> is matching for a Entity. If we invoke an Intent with that phrase, the result obtained would be something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*8xEMSU1dyq0PVwH3Ca0hEQ.png" /></figure><p>But if we mark the original value, the result would be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*eOUJ9HUANky9EHy13UySiw.png" /></figure><p>If we choose to choose the original option, the Intent will literally return what the user said and if we leave it in default, the Intent will return the value interpreted by the Entity. And what kind of values can we obtain according to the Entity? Well, that depends on what entity we’re working, for example:</p><h4><strong><em>System Entities</em></strong></h4><p>As you know, Dialogflow manages its own entities that greatly help to identify common data in a conversation. This means that we do not have to create any entities of any kind on our own in the Dialogflow console. Among some of them we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*QkMGWXUlfMY4GNDKqkG7kQ.png" /><figcaption>Dialogflow Entities by Dan Imrie-Situnayake</figcaption></figure><p>There are many other system variables, you can find more information about them in the following <a href="https://dialogflow.com/docs/reference/system-entities"><em>link</em></a>. Also there are many ways in which we can use the entities of the system, here are some examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*tlqUvyH-opmc-Wap3uoF_A.png" /><figcaption>Dialogflow Entities by Dan Imrie-Situnayake</figcaption></figure><p>During this post we have used @sys.date a lot, so let’s use another one like @sys.unit-length. If we receive “<em>ten meters</em>”, as a result we’ll obtain: {“amount”:10, “unit”: “m”}; unless we use the “original” property we saw earlier and as a result we would get “ten meters” again.</p><blockquote>Remember that all values are returned by Dialogflow as JSON</blockquote><h4>Developer Entities</h4><p>If we have everything in the <em>System Entities</em> that Dialogflow handles most commonly, what about what it doesn’t handle? There is no such thing as @sys.bikes. So. . . What should we do? Create our own entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*1daLcdVnVAxOZ013oAW8Tg.jpeg" /></figure><p>First go to the left navigation bar and then go to the Entities section, then click on the Create Entity button and let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFl8M-qov3ByC4tKr9YCAw.png" /><figcaption>Dialogflow Console</figcaption></figure><p>The first thing we will find is a screen where the following main data are required: <strong><em>Entity Name, Primary Value (Reference Value) and Synonyms.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*d4sXtgJTenaxemN4o8_YoQ.png" /><figcaption>Entities Panel — Dialogflow Console</figcaption></figure><ul><li><strong><em>Entity Name: </em></strong>The name that will identify the entity we are going to create.</li><li><strong><em>Reference Value: </em></strong>Main word that will serve as a tag to group other phrases with the same semantic value.</li><li><strong><em>Synonyms: </em></strong>Similar words that represent the same semantic value as the <em>Reference Value</em>.</li></ul><p>So, let’s take the bicycle shop as an example, the first thing to create is the entity that contains the types of bikes, let’s call it the @bike-type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*FdWLJOmmK84BNfgl4KStkw.png" /></figure><p>We now have an entity called <strong><em>bike-type</em></strong> with three values, Road, Mountain and Cross bike, each with their respective synonyms. And now with this, we can identify the variables we need when the user asks us something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*gyW0ysUD8ApOQnOgliN9Ug.png" /></figure><p>Remember that these entities will never return the synonym, on the contrary the Reference Value, unless you select <em>value.original</em> as we saw <a href="#e100">above</a>. But wait!!, we’re missing a feature of our entities: <strong><em>Automated Expansion</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*ER2OMWFS99j1SyJIFVmsXA.png" /><figcaption>Automated Expansion Option — Dialogflow Console</figcaption></figure><blockquote><strong><em>Automated Expansion - </em></strong>Allows your agent to capture words beyond those defined in your entities list by analyzing both the position and meaning of entities in your intents example phrases. by Dan Imrie-Situnayake</blockquote><p>It’s a great feature that it practically allows our entity to grow on its own. Obviously it’s always better to have all the possible options mapped out, but in case we are missing one, Dialogflow can help us with that.</p><p>What about if the entity we want to create is a little more complex? A case that happened to me some time ago is that I wanted to capture the value of my country’s currency, the Peruvian Sol (Sol Peruano - PEN). Perhaps you could tell me: for coins there is <strong><em>@sys.unit-currency</em></strong>. So let me tell you that my currency is not yet supported by Dialogflow. I hope someday yes 😆. Then what could I do? I could use a system variable to always capture a numerical value near the word “sol” or “soles” (Spanish words that in English might sound like Sun). But I would leave aside the word “Sol” or “Soles”, and if someone said something that begins with “Sol” and didn’t refer to the currency of my country? Well, I found a way out of my dilemma. <strong><em>Composite Entities.</em></strong></p><h4><strong><em>Composite Entities</em></strong></h4><p>When you need to conceptualize an entity with more than one attribute, something more complex than a system entity or a normal entity created by us, you can build your <strong><em>Composite Entity.</em></strong></p><p>Let us take the example of the currency of my country: the “Sol Peruano” (PEN). There are only two possibilities to say it, in singular or plural (<em>Sol</em> or Soles). An important point to take into consideration is the amount, it would be too long to create an entry for each possible number so I can use a system entity to capture the amounts. With that in mind, we can build our <em>composite entity</em>.</p><p>First we created an entity that houses the variations of the “Sol” currency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*lSpKVV41U7x56Y-QOdID-g.png" /><figcaption>“Centimos” is a variation for lower values of the “Soles”, such as cents of dollar.</figcaption></figure><p>Then, we create an entity that contains the types of the “Soles” and the amounts that the request may contain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*mgrnmc624JV3kvIUNrJN-w.png" /></figure><p>In order to create your composite entity, you must <strong><em>turn off synonyms</em></strong>. After that you refer the entities you need, for the amount we will use a “number” system entity, and to identify the currency, we mention the entity we created previously. Let’s not forget to put a name for the variables of each entity, otherwise we won’t be able to get the values of what the user says correctly.</p><p>Summary, our entity uses:</p><ul><li><strong><em>Mount</em></strong>: Value of type @sys.number. This will represent the numerical amount of my currency.</li><li><strong><em>Currency: </em></strong>Value of type @pen-types. This will represent the type of currency I am using.</li></ul><p>If we invoke our intent with a phrase like: My road bike costs 20 soles? we can get the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*yrtqbSpoq_1Ex6tVZ659mg.png" /></figure><p>Where currency parameter is “Sol” and the mount parameter is 20.</p><p>And last but not least we have the <strong><em>User Entities</em></strong>. These entities are updated per user session, so they usually only last 10 minutes. These types of entities need to be created from the console for then you can modify their content. However, you can also create them from the API. For example, let’s assume you want to list hospitals, restaurants, museums or something specific about a city. If we first chose London we would have a list of museums, for example, very different if we had chosen Paris or Peru. For more information about this type of entities visit this <a href="https://dialogflow.com/docs/reference/agent/userentities">Link</a>. I think I’ll need an exclusive post for this section. 🙄 🤔</p><h3>Conclusion</h3><p>It’s good that we have well defined our Intents for everything that the user can say, however it’s just as important to define our Entities, since as I said at the beginning, it’s useless to know that your other party is talking if you don’t understand what it says or do not understand the important information of what it wants to say.</p><h3>References</h3><ul><li><a href="https://dialogflow.com/docs/entities">Entities overview | Dialogflow</a></li><li><a href="https://googlecloud.tips/tips/022-dialogflow-composite-entities/">Composite entities with Dialogflow * Guillaume Laforge</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkzdL6GxJ_WY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkzdL6GxJ_WY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkzdL6GxJ_WY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/869562f69fd9ddc4cb5ed74e9c8f226d/href">https://medium.com/media/869562f69fd9ddc4cb5ed74e9c8f226d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3353170f52a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/picking-up-specific-information-to-your-conversation-entities-in-dialogflow-3353170f52a6">Picking up specific information to your conversation | Entities in Dialogflow</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Surface Capabilities in your Actions]]></title>
            <link>https://medium.com/orbismobile/playing-with-surface-capabilities-in-your-actions-8f1e5ade335b?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f1e5ade335b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[actions-on-google]]></category>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Sun, 12 Aug 2018 22:38:54 GMT</pubDate>
            <atom:updated>2018-08-12T22:38:54.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j35EYT_k6PZKLmO7T2ex_A.png" /></figure><p>One of the most important points when doing our Actions is to clearly define your conversational flow. What paths to take if the device with Google Assistant has or doesn’t have a screen?, has a web browser or not?, has sound at least?. All this is important to map to define the flow correctly and give the best user experience. It’s at this point that we enter the concept of <strong><em>Surface Capabilities</em></strong>.</p><p>You can define the features your application will support. Whether the use of a screen, sound, or web browser will be restrictive. All this was defined from your Action on Google panel. You can access it from your project panel, clicking on <strong><em>Surface</em></strong> in the left panel, and then on the right screen choose what conditions your application will support.</p><h3><strong><em>Surface Capabilities</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufxDfmT5FHbfgnVSHpm8RQ.png" /><figcaption>Action on Google Platform</figcaption></figure><p>For example, in the image, I have put that none of the above features are necessary or restrictive, so my application will be available on any device with Google Assistant.</p><p>But for example, if I defined that a screen is necessary to display information, then my application would no longer be available for any version of Google Home. And don’t worry, the console will always be warning you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwcIeLl65hy50hhpRE8Iqw.png" /><figcaption>Action on Google Platform</figcaption></figure><blockquote>All right, but how would you handle this on runtime? 🤔</blockquote><p>We can also manage the <strong><em>Surface Capabilities</em></strong> from our code/platform and treat them in runtime.</p><h3>Runtime Surface Capabilities</h3><p>When we work on our actions and we consider the runtime behavior, we found different kids of situations. For example, always display information on visually appealing cards, or using multimedia controls or even having the same information structure regardless of how it’s presented to us.</p><p>The <a href="https://developers.google.com/actions/assistant/surface-capabilities#runtime-surface-capabilities">documentation</a> tells us about the 3 most common cases that can occur when we work on our actions:</p><ul><li>Response branching</li><li>Conversation branching</li><li>Multi-surface conversations</li></ul><h4>1 - Response Branching</h4><p>Imagine you want to make an application to tell you the time, weather or even the current dollar value. If you have a Google Home and you ask him about the current value of the dollar, He can tell you audibly without problems. And if you do it from a phone, you could attach a picture to your answer that complements the answer.</p><p>In other words, in this kind of case, neither the flow nor the structure of the information must changes by the type of surface.</p><p>The Actions library provides us with constants that help us identify the type of surface we have available. We can access them with the help of the conversational interface “<strong><em>conv</em></strong>”, and the use of the “<strong>surface</strong>” class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zW9ZD6EM3EeWx1uGypkFBg.png" /><figcaption><strong>surface.capabilities.has</strong> function | Actions Library</figcaption></figure><p>Let’s make a small example and define an attempt, where we ask the current value of the dollar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zfm3xLK5bhSD0GaqpvpEXg.png" /><figcaption>actions.capability.SCREEN_OUTPUT</figcaption></figure><p>As you can see on line five, I’m checking to see if my current device where the action was invoked, is supporting some kind of screen, through the <strong><em>conv.surface.capabilities.has</em></strong> function, where the parameter to perform this verification is: <strong><em>actions.capability.SCREEN_OUTPUT</em></strong></p><pre><strong>conv.surface.capabilities.has</strong>(<em>&#39;actions.capability.SCREEN_OUTPUT&#39;</em>);</pre><p>So now, the situation is simpler than it seemed at first, now we simply have a situation of truth or falsehood. If it’s true, we put the desired text plus any image <em>(line 8)</em> that we need to enrich the answer otherwise, if we don’t have a screen, we simply proceed to speak the answer. It’s important noting that in either case, the flow of the app as well as its response have not changed, the only thing that changed is how the information was shown.</p><h4>2 - Conversation Branching</h4><p>Well let’s face it, there are certain application flows that can be a bit long and tedious with only voice commands, while on a screen that receives all the user inputs, the process is shorter and faster.</p><p>Imagine for example that you need to give to the user a set of options to choose, each one with different descriptions, then you have two options, read them one by one next to their descriptions 😐, and in case the user doesn’t understand well, you should have to repeat all the options again 😱 😨 or, you can show everything in a carousel of cards with all the necessary information and navigate between them until you choose the desired option with peace of mind.</p><p>Then, it means that we have to divide certain flows of our application according to the type of <strong><em>Surface</em></strong> that the <strong><em>assistant</em></strong> has available at the moment.</p><blockquote>So, how do I indicate what “Intent” should react according to the type of Surface? 🤔</blockquote><p>With Contexts!!!. Just as our “<em>Intents</em>” may receive <em>contexts</em> defined by ourselves or some other particular “<em>Intents</em>”, the Assistant also launches its own <em>contexts</em> according to the type of device where it’s running, so that it can be easily recognized. We have the following types of <em>contexts</em> defined with respect to the <em>Surface</em> that can be launched:</p><ul><li>actions_capability_audio_output - The device has a speaker.</li><li>actions_capability_screen_output - The device has an output display screen.</li><li>actions_capability_media_response_audio - The device supports playback of media content.</li><li>actions_capability_web_browser - The device supports a web browser.</li></ul><p>We just have to choose under what <em>context</em> we want our <em>intent</em> to be trigger and place it as an <strong><em>input context</em></strong> in our Intent in the Dialogflow console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*hbXc_bprZWc-7AEaYwt_Jw.png" /><figcaption>Dialogflow Panel — Intents</figcaption></figure><p>For example, here a Intent that will only trigger on surfaces with screens using the <strong><em>actions_capability_screen_output</em></strong> context:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*KKkeGfhuP8F-DGpRdYjnvw.png" /><figcaption>Action on Google Documentation</figcaption></figure><h4>3 - <strong>Multi-surface Conversations</strong></h4><p>Now we’ll get into the case that we’ve started a conversation from Google Home where we’re looking for information about something in particular, the conversation has gone very well, but in the end, you need to see the resulting information on some screen. What are you doing? We move the conversation somewhere else. Literally 😆.</p><p>To move the conversation to another site, we first need to verify that it is available. In this case, we want to move from a situation where we don’t have a screen to show data, to a place where we do.</p><p>Let’s verify that you have a screen available to work, otherwise you will not be able to continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LefTcOe676lXWit7LU-llg.png" /></figure><p>Using the function <strong><em>conv.available.surfaces.capabilities.has() </em></strong>we make sure we know if there is a screen available on the current user where to send the data we need, such as their Android or iOS phone. The only function that asks is what type of surface we are looking for, in our case SCREEN_OUTPUT.</p><p>If the above function returns true, it means that if we have a place to send our data but, how do we do it?, using the <strong><em>NewSurface()</em></strong> class.</p><blockquote><strong><em>NewSurface() — </em></strong>Requests the user to switch to another surface during the conversation. (<a href="https://actions-on-google.github.io/actions-on-google-nodejs/classes/conversation_question.newsurface.html">Action on Google Documentation</a>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gb6LbKsvLiA5XgfYctVBpA.png" /></figure><p>For create a <strong><em>NewSurface</em></strong> request, we need 3 parameters:</p><ul><li><strong><em>Capabilities:</em></strong> What kind of capabilities we look at for. In this case, only SCREEN_OUTPUT</li><li><strong><em>Context: </em></strong>The Assitant will ask permission (obviously) to send you data to your phone. <strong><em>Context</em></strong> gives a general idea of what will be sent when the assistant asks you if it has your permission to send the information to a new screen.</li><li><strong><em>Notification: </em></strong>This is the title of how the notification will appear on our phone.</li></ul><p>You can start trying this, either from the emulator or from your own Google Home, but it has to be an Assistant without a screen in order to test the features of move the conversation to another device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjZgzhCEN57EUpytnx6pkA.png" /><figcaption>Action on Google Platform Simulator</figcaption></figure><p>As you can see, I’m using the emulator but with the <strong><em>Surface</em></strong> setup in Google Home to simulate the startup of our app in a assistant without screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*u9sS0LGxXWW0iY-AmFZLAw.png" /><figcaption>Surface Speaker (e.g. Google Home)</figcaption></figure><blockquote>Please note that both your Simulator or the Google Home that you’re using, and the device where you want to send the notification, must both be configured with the same Google Account in order to work together.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a46tnDuJorbThuKeNHGfgA.png" /><figcaption>Status Bar — Android Device</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-3-RJxb75NNX3v5KD7QQA.png" /><figcaption>StatusBar expanded — Android Device</figcaption></figure><p>If you gave permission in the conversation to send the information to your phone, a notification should have arrived on your device, in my case I’m using my Android Device.</p><p>Remember that the title of your notification was defined earlier in your code.</p><p>And we launch our new screen requirement and that’s it all? Well, no. We need to catch this <strong><em>event</em></strong> in the Dialogflow console through an <strong><em>Intent</em></strong> with the actions_intent_NEW_SURFACE event, because when the user clicks on the notification, you must manipulate what should happen next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*XdOz0JdSF7u3hJo2fJ7TxA.png" /><figcaption>actions.intent.NEW_SURFACE in Dialogflow Console</figcaption></figure><p>Then we can handle it through our webhook when it is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FmYMPY_boyGpwTZeJxaYQ.png" /></figure><p>First I verify that the status of the new request is fine (line 2), and then I paint the result as I would like, for this example I used a <a href="https://developers.google.com/actions/assistant/responses#browsing_carousel">BrowseCarousel</a>. This time I am certain that I have a screen where I can show a more enriched answer.</p><p>And that’s all, now we have a conversation that started in a Google Home but continued on our phones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*qPkvEGrgGqrR-1psh24kzQ.gif" /></figure><h3>Conclusions</h3><ul><li>Before developing your application, it’s always good to <strong><em>map the entire flow of your application</em></strong>. This will make it easier to understand in what situations you need a screen or just sound in your application.</li><li>Remember that you can limit <strong><em>Surface Capabilities</em></strong> from your console or at runtime with the help of the SDK in your webhook.</li><li>Always try not to interrupt the conversation to the user, give them alternate flows when you don’t have a <strong><em>Surface</em></strong> available, but always in the end, give the user what they came to look for in you.</li></ul><h3>References</h3><ul><li><a href="https://developers.google.com/actions/assistant/surface-capabilities">Surface Capabilities | Actions on Google | Google Developers</a></li><li><a href="https://actions-on-google.github.io/actions-on-google-nodejs/classes/conversation_question.newsurface.html">NewSurface | actions-on-google</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f1e5ade335b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/playing-with-surface-capabilities-in-your-actions-8f1e5ade335b">Playing with Surface Capabilities in your Actions</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conociendo Stubs y Mocks]]></title>
            <link>https://medium.com/orbismobile/conociendo-stubs-y-mocks-30689161f8a3?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/30689161f8a3</guid>
            <dc:creator><![CDATA[Andru]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 15:40:15 GMT</pubDate>
            <atom:updated>2018-08-10T15:40:15.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Cuando desarrollamos aplicaciones consumiendo API’s o servicios web de terceros en nuestra app, tenemos la limitante de programar dependiendo de la disponibilidad del servicio, dado esta situación, nace la interrogante ¿Podría desarrollar mi app sin hacer uso de servicios?, la respuesta es <strong>Claro que si! 😉.</strong></p><p>Para lograrlo necesitamos usar <strong>stubs</strong> y <strong>mocks 🤙.</strong></p><h3><strong>Conceptos básicos</strong></h3><h3>Stubs</h3><p>Son aquellas funciones que se comportan como “relleno” ya que sustituyen a las funcionalidades que realmente dependen de nuestro código.</p><blockquote>Una funcionalidad viene a ser una orden o conjunto de órdenes que tienen uno o muchos propósitos, Ej: Calcular la suma de 2 números ó retornar el precio total a pagar de un carrito de compras. 🤖</blockquote><p>Por ejemplo, tenemos la siguiente función que tiene cierta lógica, llamada <strong>randomNumber:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df9a6ab701ec2b2ec4da8b08cdff970/href">https://medium.com/media/8df9a6ab701ec2b2ec4da8b08cdff970/href</a></iframe><p>Ahora aplicamos un <strong>stub</strong> en base a la función de arriba:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/279841afe6ba3e737303ab2f209a173d/href">https://medium.com/media/279841afe6ba3e737303ab2f209a173d/href</a></iframe><p>Como se visualiza, esta última función realiza una salida fija pero con el nombre <strong>randomNumber:</strong></p><p>Ahora tenemos el siguiente ejemplo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/685bff505c0063c164239f0d2810025e/href">https://medium.com/media/685bff505c0063c164239f0d2810025e/href</a></iframe><p>En este ejemplo, tenemos 2 parámetros de tipo función, que son <strong>success </strong>y<strong> fail</strong>, en este caso, necesitamos crear 2 <strong>stubs </strong>para cubrir el escenario en donde se ejecutará el parámetro <strong>success</strong>, y otra para el parámetro <strong>fail:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b519b8c10eb9e8406b243bb6af77fe5/href">https://medium.com/media/2b519b8c10eb9e8406b243bb6af77fe5/href</a></iframe><h3>Mocks</h3><p>Es muy similar a un <strong>stub, </strong>pero la diferencia es que se dedica a ser una copia de un objeto o de una clase, eso quiere decir de que aprovechamos el uso de protocolos para poder definir nuestros métodos que una clase debe tener:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/475dda35152345d1e23b86543a8fcf06/href">https://medium.com/media/475dda35152345d1e23b86543a8fcf06/href</a></iframe><p>Y normalmente lo usamos para crear una <em>clase original</em>* que implementará el protocolo, nuestra clase se llamará <strong>UserActions:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a40c8c81f7d0d25e431432defab40ff/href">https://medium.com/media/9a40c8c81f7d0d25e431432defab40ff/href</a></iframe><p>Ahora, implementamos nuestro protocolo a nuestra clase que toma el rol de mock, lo llamaremos <strong>MockUserActions</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7caed180ec47d5618dd449d8f404b833/href">https://medium.com/media/7caed180ec47d5618dd449d8f404b833/href</a></iframe><blockquote>Una clase original nos referimos a la clase que interactúa con data o servicios reales, o contiene la lógica de negocio de nuestro proyecto o aplicación.</blockquote><h3>Caso de uso</h3><p>Vamos a hacer una aplicación que facilite la búsqueda de libros por autor bajo el servicio de <a href="http://openlibrary.org/">openlibrary.org</a>, y a la vez, listar/guardar los libros que deseo leer mas tarde.</p><p>Para ello realizamos un paquete en swift bajo docker, el código completo lo puede ver <a href="https://github.com/andru255/swift-stubs-mocks">aquí</a>.</p><p>Este es el diagrama de clases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRC50waRJrdl0wce5KiYXA.png" /></figure><h3>Aplicándolo en pruebas unitarias</h3><p>Bajo una suite de pruebas unitarias, los <strong>stubs</strong> y <strong>mocks</strong> extienden su uso manteniendo su escencia, según el genial post <a href="http://martinfowler.com/articles/mocksArentStubs.html">Mocks aren’t stubs</a> de <a href="http://www.martinfowler.com/">Martin Fowler</a>, nos explica no solamente de la confusión que suele pasar entre los <strong>stubs</strong> y <strong>mocks</strong>, sino también acerca de <strong>fakes</strong> y <strong>dummies</strong> 🤯.</p><p>En este caso nos centraremos en lo que define como <strong>stubs </strong>y <strong>mocks </strong>considerándolos como <em>dobles.</em></p><blockquote>Los dobles así como en las películas, donde en las escenas de alto riesgo se juegan la vida, en el ámbito de desarrollo, los dobles toman el lugar de nuestras funciones y clases originales.</blockquote><p>Con esto en mente, lo aplicaré creando un paquete swift que crearé bajo:</p><ul><li>Sistema operativo: linux/ubuntu</li><li>Versión de Swift: 4.0</li><li>Suite de testing: <a href="https://github.com/Quick/Quick">Quick</a></li><li>Para pruebas unitarias: <a href="https://github.com/Quick/Nimble">nimble</a></li></ul><h3>Stubs</h3><p>Nos ayuda a resolver las siguientes preguntas cuando desarrollamos:</p><ul><li>¿Mis pruebas unitarias funcionarán sin problemas cuando reemplace mi función original con un stub?</li><li>¿Están preparados todos los escenarios tanto satisfactorios y fallidos cambiando mis funciones originales por stubs?</li></ul><p>Como vemos, el uso de <strong>stubs </strong>bajo pruebas unitarias nos ayuda a verificar el <strong>estado </strong>de una función en nuestra aplicación, eso quiere decir, validar la responsabilidad de nuestra función original.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8083ab04f2468fb9781109066c0df81/href">https://medium.com/media/c8083ab04f2468fb9781109066c0df81/href</a></iframe><p>Como se visualiza, con estos stubs se simula los escenarios que puede suceder con el método <strong>request</strong></p><h3>Mocks</h3><p>Nos facilita resolver nuestras dudas como:</p><ul><li>¿Se definió mi función?</li><li>¿Se ejecutó mi función?</li><li>¿Cuántas veces estoy ejecutando una función?</li></ul><p>Estas preguntas hacen que cuando manejamos <strong>mocks </strong>bajo pruebas unitarias, estos se orienten a verificar el comportamiento de nuestra función, y para ello lo aprovechamos mediante el uso de clases y protocolos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/986451ec68b8243ffc7bcff7d975a9df/href">https://medium.com/media/986451ec68b8243ffc7bcff7d975a9df/href</a></iframe><p>Como se visualiza, definimos una clase mock que simula la clase <strong>BookFinder</strong></p><h3>Usando nuestros stubs y mocks</h3><p>Teniendo nuestras definiciones, como resultado tenemos las siguientes pruebas unitarias:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74752a8b310daa0079f84f8c84402fe4/href">https://medium.com/media/74752a8b310daa0079f84f8c84402fe4/href</a></iframe><h3>Mocks Parciales y completos</h3><p>Al aplicar mocks, existen 2 tipos, los <strong>parciales</strong> y <strong>completos</strong>, estos son fáciles de detectar ya que un <strong>mock parcial </strong>simula una parte de una clase, mientras los <strong>completos </strong>son los que cubren todas las funcionalidades de una clase en base al protocolo definido.</p><h3>Referencias</h3><ul><li><a href="https://www.swiftbysundell.com/posts/mocking-in-swift">Mocking in Swift by Jhon Sundell</a></li><li><a href="https://www.genbetadev.com/javascript/desmitificando-los-dobles-de-test-mocks-stubs-and-friends">Desmitificando los dobles de test: Mocks, stubs and friends</a></li><li><a href="https://lvsti.github.io/cocoagrinder/2017/01/06/lightweight-object-mocking-in-swift.html">Lightweight Object Mocking in Swift by @lvsti</a></li><li><a href="https://cocoacasts.com/how-to-mock-and-stub-a-system-class-in-swift-part-1">How to Mock and Stub a System Class in Swift</a></li><li><a href="https://academy.realm.io/posts/tryswift-veronica-ray-real-world-mocking-swift/">Real World Mocking in Swift</a></li><li><a href="https://qualitycoding.org/swift-mock-objects/">How to Design Swift Mock Objects — Quality Coding</a></li><li><a href="https://www.objc.io/issues/15-testing/mocking-stubbing/">Test Doubles: Mocks, Stubs, and More — objc.io</a></li><li><a href="https://www.raywenderlich.com/101306/unit-testing-tutorial-mocking-objects">Unit Testing Tutorial: Mocking Objects</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30689161f8a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/conociendo-stubs-y-mocks-30689161f8a3">Conociendo Stubs y Mocks</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Considerations when making External requests in your Actions]]></title>
            <link>https://medium.com/orbismobile/considerations-when-making-rest-requests-in-your-actions-a98e5dc35dd9?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/a98e5dc35dd9</guid>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[google-actions]]></category>
            <category><![CDATA[actions-on-google]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 02:50:18 GMT</pubDate>
            <atom:updated>2018-09-26T05:03:38.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*81zL0JnD-yRevch7QbqPyQ.jpeg" /></figure><p>Probably during the development of your first Actions (App for Google Assistant), you added thousands of intents, different kinds of answers, language support, and everything you could, until you said, okay, it’s time to connect to some external API.</p><p>There are many ways that you can work it, as well as many libraries, many ways, many other good practices. I don’t pretend to be a definitive list, just an opinion on the things I’ve been through and would like to share. Well, let’s get started!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxTkcELz3rjpLDDRAOI%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxTkcELz3rjpLDDRAOI%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxTkcELz3rjpLDDRAOI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/303471110c3284eee20ee60a86c77658/href">https://medium.com/media/303471110c3284eee20ee60a86c77658/href</a></iframe><h4><strong>1 — Separate your constant and common config</strong></h4><p>Regardless of whether you use a third-party library or native libraries, there will always be a base url where you can make your requests, it is good to have this information in a separate object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*yJqSM3D4Tcv55o6TxYmPbA.png" /></figure><p>And then, you can use in any part of your code, something like this:</p><pre>url: ApiConstant.BASE_URL</pre><h4>2— Javascript is Synchronous, work with promises</h4><p>Nowadays exists many and different libraries for make request in NodeJs, so It’s important to know which one to use based on its features. And I consider one of the most important is that it works with Promises or make them yourself.</p><p>Why?, Because remember:</p><blockquote>JavaScript is a synchronous, blocking, single-threaded language. That just means that only one operation can be in progress at a time. (<a href="https://medium.com/@kvosswinkel/is-javascript-synchronous-or-asynchronous-what-the-hell-is-a-promise-7aa9dd8f3bfb">Kait Hoehne</a>)</blockquote><p>So, it’s probably that you may have problems when you run a request and it takes a while for it to respond, until then your Action will launch a <strong><em>Timeout Exception</em></strong>. But with promises you can solve it. Here are some interesting libraries.</p><p><strong><em>Work with Promises</em></strong></p><ul><li><a href="https://www.npmjs.com/package/axios">Axios</a> — Promise based HTTP client for the browser and node.js</li><li><a href="https://www.npmjs.com/package/got">Got</a> — Simplified HTTP requests</li></ul><p><strong><em>Work without Promises (remember here make your owm promises)</em></strong></p><ul><li><a href="https://www.npmjs.com/package/http">HTTP</a> — The standard library</li><li><a href="https://www.npmjs.com/package/request">request</a>- Simple to use</li></ul><p>I know there are many others available, remember that you are always free to choose the one that best suits your needs. 🙂</p><h4>3 — console.log() A great ally 😎</h4><p>I know that the Google console gives us a lot of help with its <strong><em>response</em></strong>, <strong><em>debug </em></strong>and <strong><em>error</em></strong> panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*NkF9MUI5OIcmz2pgWhkPqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pyx1_rVi3CYmqU0hV0bIGQ.png" /><figcaption>Response &amp; Debug Tabs in Action on Google Console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaEs9gxDdTP3bkNs2lY0DQ.png" /><figcaption>Error Tab in Action on Google Console</figcaption></figure><p>But sometimes we need more information in order to see in detail what really happens behind our code. All you need is a <strong><em>console.log(</em></strong>whatever you need<strong><em>) </em></strong>to be able to look more closely at details that may go unnoticed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*dqGjhYuUC2usprVJiLkxGQ.png" /><figcaption>Hi, I’m a console.log()</figcaption></figure><p>And where do I see the logs? Well, you can choose from the <strong><em>Google Cloud Platform</em></strong> or <strong><em>Firebase Console. </em></strong>Remember to use a <strong><em>tag</em></strong> to help you filter them quickly, I always use Tohure, it’s my nickname 😆.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hADDPyQopmuSLfaNhlEOg.png" /><figcaption>Google Cloud Plantform</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qYe_VDMT2mM7Z_ZzB9KxQ.png" /><figcaption>Firebase Console — I prefer this one, don’t tell anyone.😄</figcaption></figure><p>Actually at this point, you may use the console.log() not only when working with request, you can use it anytime actually, I just wanted to mention it in case I forgot.</p><h4>4— Dont repeat the same query, only save the first result</h4><p>I know it’s strange that I say that, but I’ve seen some people repeat the same query just so that the Assistant can give the result again in case the user needs it again. However this represents another query, another expense and another request, remember time is money.</p><p>So what can I do? Save the data in the session. How? With the <strong><em>conversationToken.</em></strong></p><blockquote>The <a href="https://developers.google.com/actions/reference/rest/Shared.Types/AppResponse#FIELDS.conversation_token">conversationToken</a> field is a string that contains an opaque token that is recirculated to the Actions every conversation turn. (<a href="https://developers.google.com/actions/assistant/save-data">Actions on Google Documentation</a>)</blockquote><p>So all we need to do is keep our <strong><em>small data </em></strong>on our object. And I say <strong><em>small</em></strong> because it’s for variables, small objects, some small list or other, it isn’t a database that can store Terabytes of information. There are other solutions for this, but I will talk about them in another post.</p><p>You can access <strong><em>conversationToken</em></strong> through the conversational interface “<strong><em>conv.data</em></strong>” and then type the names of the parameters that you want to store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*N6sn_nfHN9ri9BzIhTjoGw.png" /><figcaption>conversationToken -&gt; conv.data</figcaption></figure><h4>5 — And last but not least. Your Plan</h4><p>Your request doesn’t work even though you’ve already checked everything? It’s likely that the error is on the other hand.</p><p>If your webhook is built on your own server or service, and depending on how it is configured, then no problem. But if you’re using <strong><em>Firebase Cloud Functions </em></strong>to make your webhook, it’s best to update your plan from Spark to Blaze.</p><p>Why? Spark plan does not allow requests to external APIs, only between Google products. It’s in the fine print.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*eHfhbPaHApzOHuKDQTHLHQ.png" /><figcaption>That’s right, it’s there.</figcaption></figure><p>But don’t worry, if you’re new to the console, Google will give you a free year to use it as you please. Also, the charge for each request is not much unless your application becomes popular worldwide. Well, in that case, if we had to think of another solution 😅.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*_UTyPBCjR0IfELEu6N_W4Q.png" /><figcaption>Always remember to use Blaze</figcaption></figure><h3>Conclusion</h3><p>And that’s it, I’m not a Javascript expert, but several of the situations mentioned in this post, they’ve happened to me and my friends. So I wanted to tell them in case anyone needs them. I’m missing some, so please write me your comments to improve this little ToDo List.</p><p>See you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98e5dc35dd9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/considerations-when-making-rest-requests-in-your-actions-a98e5dc35dd9">Considerations when making External requests in your Actions</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello, Salut & Hola? Internationalization in your Google Actions]]></title>
            <link>https://medium.com/orbismobile/hello-salut-hola-internationalization-in-your-google-actions-772a63989c10?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/772a63989c10</guid>
            <category><![CDATA[actions-on-google]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[google-actions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-assistant]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Tue, 07 Aug 2018 01:09:10 GMT</pubDate>
            <atom:updated>2018-08-07T17:02:14.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*jdPeMmAlMrzaZCXxZ_wTsg.png" /></figure><p>When Google Assistant was released, it was only available in English, and it was great at the time, however, its growth was such that it was necessary to work on its availability for different languages.</p><p>Since then, thanks to the support of Google and the communities we have Google Assistant available in different languages: English, German, French, Japanese, Korean, Spanish and many others.</p><p>And why am I saying all this? Because you’ve probably did something like this with your Google Assistant configured in English:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i399u82_cA3UHN4UlxEIDw.png" /><figcaption>I know you did too. Don’t even try to deny it.</figcaption></figure><p>It’s likely that the result was not as expected 🙃. To avoid these lapses, we’ll work on the internationalization of our application. But before we start, let’s review a couple of terms that are necessary to know:</p><ul><li><strong><em>Language:</em></strong> An agreed upon, spoken and written mode of communication.</li><li><strong><em>Region:</em></strong> A defined physical area that’s usually associated with a country.</li><li><strong><em>Locale:</em></strong> The combination of a language and region.</li></ul><p>It’s important to know all this since the pronunciation, meaning and even the way of pronouncing a language, changes in each country and even within the localities of each country. Things to keep in mind when you start working on your applications.</p><p>Knowing that, let’s start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_lJU7PtU1b84VgEUm-5ldQ.gif" /></figure><p>First, we need to configure the languages that our actions will support. To do this, we have two ways. Through the <strong><em>Actions on Google</em></strong> console or through the <strong><em>Dialogflow</em></strong> platform.</p><h3>Actions on Google Console</h3><p>In the left panel of the console, you’ll have the Actions option, in the Build section, you must click on it to see the language options of your actions or add more of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*WZCo2mEyzosCPpwqyOPm_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*TYzElHpTjRePZ_ttt7u-Cw.png" /></figure><p>Not only will you be able to add the language you want your application to support, also the available location that has the assistant. Such as American English or British English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*ye2BaSWOXwG-z3pN5C25TQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*EW_8L0AeSIwKflbWbhd34w.png" /></figure><p>It’s important to keep this in mind as we must seek to give the best user experience when creating our applications. For example, there’re different variations of English: British, American, Canadian, Australian; each with different accents, or even the meaning of some words changes. That’s why it’s important to keep this in mind in order to offer users the best conversational experience with the assistant.</p><h3>Dialogflow Platform</h3><p>The same procedure we did on the Actions on Google platform, we can do from the Dialogflow platform. Click on the cross button on the left side of our project panel to enable more languages for our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*MqOkiZcGI4Ba9VUOxTa9Jw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*4CnK_ydd7r2xnk9wjwYEhg.png" /></figure><p>As with the Actions on Google platform, we can not only add the language we want, also the supported localizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*d1HF3XmeD_LV6tklev1lLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*qtzUatrUjumChtmU7ZtjbQ.png" /></figure><p>Up to this point, we’ve only defined the languages that will be supported by our application. However, we still have to customize the behavior of our actions in each language. And for this, we’re going to work in two parts:</p><ul><li>Customize the application on the platform</li><li>Customize our WebHook</li></ul><h3>Customizing the application on the platform</h3><p>Each language added from any platform (Actions on Google or Dialogflow), will be reflected in the other by being connected. In other words, if I add a language from the Actions on Google console, it’ll be reflected in Dialogflow and vice versa.</p><p>The added language will be displayed in the left panel of the Dialogflow platform, and if more than one has been added, the remaining language will be displayed in the three-dot button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*oY9HbzekHbOsIJ2gvDZKVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*GTkyrtb7PTapcgqe6LX_9A.png" /><figcaption>Dialogflow panel</figcaption></figure><p>The best part of all this is that Dialogflow automatically creates a replica of every attempt or entity we have previously created, or continue to create thereafter, for every language we set up in our application. So we don’t have to re-create everything from scratch. However, be careful, since it creates a replica of intents or entities, but not of their internal values. We need to customize each section in order to have the answers we want in each language.</p><h4>Intents</h4><p>For example, here I have the same intent but in two different languages (English and Spanish).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*WutdIkjC4Xo00yCJTvmFGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*0Ijzzp04BM2bTf-DHSMzVw.png" /><figcaption>English left — Spanish right</figcaption></figure><p>Don’t worry about the variables you use in your intents, the name of these is also replicated in each language, just don’t try to change it in each language, because you could have problems when trying to homologate those variables in your webhook later. So remember that you should always have the same thing in all languages and their variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*eFdSX8U5R9Qb-IWQpN24VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*j0OVr6FinJ1NmxUMlYc_Ig.png" /><figcaption>English left — Spanish right (Right way)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*hLG9CfRaXLHatsGw6SA2Wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*7PHwc6SFy_-zU385x5HnLg.png" /><figcaption>English left— Spanish right (Bad way)</figcaption></figure><h4>Entities</h4><p>In the case of entities, the same thing happens as with intents. Each entity is replicated for each added language.</p><blockquote><strong><em>However, here we must take special care.</em></strong> Although the names of the entities are the same, the values change according to each language. If you have a conditional or index of an entity tied to these values in your webhook, you probably have an error, because the value will always change according to the language.</blockquote><p>My recomendation? Always have the same name in the “references values” and only vary the “synonyms” for each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*myt4v4fLXiufxx6748ZRkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*S7XqXX2o4f8Qv7327T33Xg.png" /><figcaption>English left — Spanish rigth</figcaption></figure><p>For now we have finished configuring our application on the Dialogflow platform. Now we have to configure our webhook to give a good experience to the user with their respective language when using our application.</p><h3>Customizing our WebHook</h3><p>In the case of the Dialogflow platform, we had a graphical interface that allowed us to switch between the languages we had configured in our application. But in our webhook, where do we get this data?</p><h4><strong><em>Getting locale</em></strong></h4><p>Suppose we have any attempt, for example “Welcome”, we will use our conversational instance “<em>conv</em>”, so we can access the <em>User class</em> and through it to the <em>locale property</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GS0E1QZkta0a-ti3450Kag.png" /></figure><p>The user class has many other properties (That you can see in this <a href="https://actions-on-google.github.io/actions-on-google-nodejs/classes/conversation.user.html"><strong><em>link</em></strong></a>), but for now, we’ll just focus on <strong><em>locale</em></strong>.</p><p>Locale will return a String with the regional language of the user configured in the Assistant, which is composed of both the language and the region we talked before. For example, ‘en-US’:</p><ul><li>en = English</li><li>US = United States.</li></ul><p>With this data we will be able to work on the type of answer we need according to the language. At first, we could work like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qV0DgbvdJXO63Utc3ozw_A.png" /><figcaption>No, I don’t think so.</figcaption></figure><p>But what would have happened if, instead of an intent or language, we had three or four?. Working with only conditionals, would have been unsustainable. So to handle our application in a more scalable way, we will use a very useful library called i18n, which will help us to manage the languages within our application.</p><h3><strong><em>Using i18n</em></strong></h3><p>This module will help us with translation through dynamic storage in json. More information <a href="https://www.npmjs.com/package/i18n"><strong><em>here</em></strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*Jw4ypwdk7jt0DqAELRGooA.png" /><figcaption>Don’t forget add the library to your dependencies.</figcaption></figure><p>The first thing is to import the library and configure it in our project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*JeT77fiQUqcj2hSi10NWTQ.png" /><figcaption>Library configuration.</figcaption></figure><p>In this part, we will see that i18n has many configuration options, among the most important for our actions we have the following:</p><ul><li><strong><em>Directory: </em></strong><em>Where to store json files — defaults to ‘./locales’ relative to modules directory.</em></li><li><strong><em>Default Locale: </em></strong>You can define a default location for those that are not available in your app.</li><li><strong><em>Object Notation: </em></strong><em>Enable object notation for use templates in your json objects.</em></li><li><strong><em>Fallbacks: </em></strong>Fallbacks<strong><em> </em></strong>(Alternatives) that you can to set manually for certain languages.</li></ul><p>i18n has many other settings that you can use, available in its <a href="https://www.npmjs.com/package/i18n#list-of-all-configuration-options">documentation</a>.</p><p>The next thing to do is to set the location to i18n, but when should we do it? The SDK handles middleware that runs just before the IntentHandler, allowing us to configure the third-party libraries we need in our application, in this case, i18n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*2styVB9JmpJeblqcGcLo5Q.png" /><figcaption>Setting up location in our i18n module</figcaption></figure><p>Let’s not forget to have our locale folder in our project with the respective files. Names should follow the Language-Region nomenclature in json format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*v9mqzGj2eayQKgNFxlVgQQ.png" /><figcaption>Project Structure</figcaption></figure><p>In this case I have two files for English (American and British) and one for Spanish in general, just as an example. Now let’s review the structure of one of these objects.</p><h3>en-US.json &amp; es.json</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*tH4gFoaGCW_oRabY0m9TXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*I7CTY9WaeOrJloVTX58KuQ.png" /><figcaption>English left (en-US.json) — Spanish right (es.json)</figcaption></figure><p>As you can see, for this case I have two properties: <strong><em>simple_hello</em></strong> and <strong><em>template_hello</em></strong>; both files have the same keys, because if they were different, we would have a problem trying to find the values in the objects.</p><p>They may look similar, however the first one is a simple <strong><em>String</em></strong>, while the second one is a <strong><em>String Template</em></strong>, this will allow us to pass values to our object and have a dynamic response. How?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-1F9GcNfup6mA-ZlTfUmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUmCg3Ra5Zqr-OgH_ToSkA.png" /><figcaption>String simple, left — String Template, right</figcaption></figure><p>See?, you only have to pass the values you require separated by commas, but the number of variables passed must be considered in your template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*5bNGzapK3O7E_vXIis1iJw.png" /><figcaption>String template with more than one parameter.</figcaption></figure><p>However, to make all this work, remember to have the <strong><em>objectNotation</em></strong> <a href="#62cd">parameter we saw above</a> in true.</p><blockquote>Hey!!!, You only have one file for Spanish, what happened with the other locations like Spain, Mexico or Peru?</blockquote><p>Keep calm 😉, remember the <a href="#3a38"><strong><em>Fallback</em></strong> parameter</a>? This parameter allows us to have a default for the languages we define.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*_r0m7gh46-xv15fFaPsPSw.png" /><figcaption>And all the languages that you need 🙂</figcaption></figure><p>And that’s it. Now you have the bases for your app to support all the languages you want.</p><h3>Conclusion</h3><p>Remember that the main reason for all this is always to give a better user experience, not only in the characteristics of the application, but also in the experience when speaking, not something mechanized, instead of, something with a human touch.</p><p>I’ve implemented a demo of it in my github, using as a base project the <a href="https://medium.com/orbismobile/my-experience-with-google-assistant-codelabs-and-why-you-should-also-take-them-right-now-8e7a77719d2c">Google Actions Codelabs</a>, which you can find <a href="https://github.com/Tohure/AssistantAppTraining">here</a>. Feel free to ask me any questions you have 🙌.</p><h3>References</h3><ul><li><a href="https://developers.google.com/actions/localization/">Build Localized Actions | Actions on Google | Google Developers</a></li><li><a href="https://www.npmjs.com/package/i18n">i18n</a></li><li><a href="https://github.com/Tohure/AssistantAppTraining">Tohure/AssistantAppTraining</a></li><li><a href="https://medium.com/orbismobile/my-experience-with-google-assistant-codelabs-and-why-you-should-also-take-them-right-now-8e7a77719d2c">My experience with Google Assistant Codelabs and why you should also take them right now!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=772a63989c10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/hello-salut-hola-internationalization-in-your-google-actions-772a63989c10">Hello, Salut &amp; Hola? Internationalization in your Google Actions</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience with Google Assistant Codelabs and why you should also take them right now!]]></title>
            <link>https://medium.com/orbismobile/my-experience-with-google-assistant-codelabs-and-why-you-should-also-take-them-right-now-8e7a77719d2c?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e7a77719d2c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-assistant]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[google-actions]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 16:14:46 GMT</pubDate>
            <atom:updated>2019-01-27T04:37:27.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*iQ7hgqKPFrL4UNUx3tS-lA.gif" /><figcaption>Pinterest — AndroBliz</figcaption></figure><p>A little over a year and a half ago, Google launched its platform to create <em>Actions</em>, the apps for the Google Assistant platform, and since then, there have been many changes.</p><p>Among the multiple fulfillment tools that exist to create your actions are platforms such as dashbot.io, Wit Lingo, Spokenlayer, Dialogflow, and many others.</p><p>When I entered the world of Google Actions, there wasn’t as much information as there is now, in fact, I had a lot of complications using Dialogflow in the beginning (formerly called Api.Ai), but after a while, I did my first action and launched it in store. However, a few months later, I was surprised that the Dialogflow API was changing from V1 to V2 and that’s why my first app slowly started to crash.</p><p>Not only the Dialogflow API, the Google Actions platform was also changing and I said to myself: Well it’s time to read again, I would like to there was a codelab of this; and that’s when on Twitter I met the user <a href="http://twitter.com/MandyChanNYC">@MandyChanNYC</a> and how she and her team created codelabs for Google Assistant. 😄😄 Yeay!</p><blockquote>And with you ladies and gentlemen, the labs.</blockquote><ul><li><a href="https://codelabs.developers.google.com/codelabs/actions-1">Build Actions for the Google Assistant (Level 1)</a></li><li><a href="https://codelabs.developers.google.com/codelabs/actions-2">Build Actions for the Google Assistant (Level 2)</a></li><li><a href="https://codelabs.developers.google.com/codelabs/actions-3/#0">Build Actions for the Google Assistant (Level 3)</a></li></ul><p>It wasn’t just a lab on how to create an action, it was a little tour of the new Google Actions platform, the flow of creating Dialogflow Intents, and how to launch your first WebHook to expand the capacity of your Actions.</p><p>While there are only Dialogflow or only WebHooks tutorials in the network, and some of both, these codelabs have the best of both worlds and in a well explained way, easy to understand for any user who wants to get into the world of Google Actions.</p><h3>What will we find in the labs?</h3><p>During the labs you will make a project that we will call Lucky Number — Your favorite color, the same project will be treated during both labs, in clear and well defined steps.</p><blockquote>You will see the explanation of how Google Assistant works from behind.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tBX3cMv2Fx3QOmAqOgdnPw.png" /><figcaption>By Codelabs Developers</figcaption></figure><blockquote>How to create an Action in Google Actions console.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*j9Z-W_wJBcd9PFTKuscDhg.png" /><figcaption>By Codelabs Developers</figcaption></figure><blockquote>How Google Assistant, Dialogflow and Firebase work together.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSj2FzWCr9C0rY1x7FfS-g.png" /><figcaption>By Codelabs Developers</figcaption></figure><blockquote>Create <a href="https://dialogflow.com/docs/agents">Agents</a> and <a href="https://dialogflow.com/docs/intents">Intents</a> in Dialogflow console.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_zxXZF0xKiEAHIUbN4O1w.png" /><figcaption>By Codelabs Developers</figcaption></figure><blockquote>Manage, Deploy and Test in the Google Action Platform</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZH6nA6ca4gXUsU6oSEfyQ.png" /><figcaption>By Codelabs Developers</figcaption></figure><blockquote>Create your own <a href="https://dialogflow.com/docs/fulfillment#webhook">WebHook</a> and interact with the variables in the Dialogflow console</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou0CnDNPPdw-xK_-Z4KVlg.png" /><figcaption>By Codelabs Developers</figcaption></figure><p>Other very important points you will see in the labs are:</p><ul><li>How to use <a href="https://firebase.google.com/docs/cli/">Firebase command-line</a> interface and use <a href="https://firebase.google.com/docs/functions/">Firebase Cloud Functions</a>.</li><li>Use a <a href="https://developers.google.com/actions/sdk/invocation-and-discovery#deep_link_invocation">Deep Links</a> in our Actions.</li><li>Use <a href="https://developers.google.com/actions/assistant/responses">Responses</a> and <a href="https://developers.google.com/actions/assistant/helpers">Helpers</a> in our Intents.</li><li>Use audio effects with <a href="https://developers.google.com/actions/reference/ssml">SSML</a>.</li><li>Add <a href="https://dialogflow.com/docs/reference/follow-up-intent-expressions">follow-up intents</a> and Custom Intents.</li><li><a href="https://developers.google.com/actions/assistant/save-data">Store Data</a> in your Conversations.</li><li>Custom reprompts and custom exits.</li><li>Visual Selectors and Rich Responses.</li></ul><h4>Challenges still to be fulfilled</h4><p>While many points have been covered in these codelabs, there are still other interesting topics to keep checking:</p><ul><li><a href="https://developers.google.com/actions/localization/">Internationalization</a> — Your application must support multiple languages if you want to reach a wider audience. (I have a little post about this <a href="https://medium.com/orbismobile/hello-salut-hola-internationalization-in-your-google-actions-772a63989c10">here</a>)</li><li><a href="https://developers.google.com/actions/transactions/">Transactions</a> — You can create purchase and payment flows in your application.</li><li><a href="https://developers.google.com/actions/assistant/surface-capabilities">Surface Capabilities</a> — There will not always be a screen to see results directly, like the Google Home, so you’ll have to play around with audible solutions. (You can visit this <a href="https://medium.com/orbismobile/playing-with-surface-capabilities-in-your-actions-8f1e5ade335b">link</a> for more information)</li></ul><h3>Conclusion</h3><p>The world of Google Actions continues growing, and new features and new integrations with the platform are emerging every day. The best of all this is the great community that continually gives support to those who wish to learn more about this. The codelabs is a great step to start and believe me, once inside, there is no turning back.</p><p>In each laboratory there are project repositories respectively. In my case I’ve developed both laboratories and I’ve added my grain of sand and I’ve put internationalization to the project to have it in English and Spanish. I hope you can always help me with feedback in my <a href="https://github.com/Tohure/AssistantAppTraining">repo</a>.</p><p><a href="https://github.com/Tohure/AssistantAppTraining">Tohure/AssistantAppTraining</a></p><h3>References</h3><ul><li><a href="https://codelabs.developers.google.com/codelabs/actions-1/">Build Actions for the Google Assistant (Level 1)</a></li><li><a href="https://codelabs.developers.google.com/codelabs/actions-2/">Build Actions for the Google Assistant (Level 2)</a></li><li><a href="https://codelabs.developers.google.com/codelabs/actions-3">Build Actions for the Google Assistant (Level 3)</a></li><li><a href="https://developers.google.com/actions/extending-the-assistant">Overview | Actions on Google | Google Developers</a></li><li><a href="https://medium.com/orbismobile/hello-salut-hola-internationalization-in-your-google-actions-772a63989c10">Hello, Salut &amp; Hola? Internationalization in your Google Actions</a></li><li><a href="https://medium.com/orbismobile/playing-with-surface-capabilities-in-your-actions-8f1e5ade335b">Playing with Surface Capabilities in your Actions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e7a77719d2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/my-experience-with-google-assistant-codelabs-and-why-you-should-also-take-them-right-now-8e7a77719d2c">My experience with Google Assistant Codelabs and why you should also take them right now!</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Descubriendo el mundo Android ]]></title>
            <link>https://medium.com/orbismobile/descubriendo-el-mundo-android-9b067348a31d?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/9b067348a31d</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[women-in-tech]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Manuela Flores]]></dc:creator>
            <pubDate>Wed, 18 Jul 2018 19:27:59 GMT</pubDate>
            <atom:updated>2018-07-18T19:27:59.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dKH5TblVSvvvo7JqJX9W6Q.jpeg" /></figure><p>En el 2017 decidí que estar en el rubro de la tecnología era en lo que me quería desarrollar profesionalmente… ¿Cómo lo decidí? — Es una buena pregunta …Prometo que esa historia será contada en un próximo post :) .</p><p>Llevo alrededor de dos meses desempeñándome como Android developer a tiempo completo , en este post me gustaría compartir como fué mi transición de desarrollo front-end a desarrollo Android.</p><h3>Mi mundo : “Desarrollo front-end 😊️“:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jwFdM0iJy8t2oonNBe4P-Q.png" /></figure><p>En mis días como front-end estuve desarrollando bajo las siguientes tecnologías :</p><ul><li><strong>HTML5</strong> .-<em> El esqueleto de todo 🔨</em>. Esto implica estructurar el contenido de una manera correcta, diciéndole al navegador dónde van textos, imágenes, videos, etc .</li><li><strong>CSS3</strong> .- <em>La parte visual del desarrollo </em>💄. Implica tener conocimientos sobre conceptos como : Responsive Web Design, Grillas, media queries, preprocesadores como SASS o LESS, frameworks como Bootstrap, Materialize ,etc.</li><li><strong>JavaScript (mi favorito 💛) </strong>.-<em> Donde sucede la magia</em> ✨. Estuve viendo conceptos de programación funcional y aprendí a usar librerías como JQuery, React, además de conceptos como SPA(single page aplication),Web Components , AJAX y uso de preprocesadores como BABEL; además, un poco de Node JS para el levantamiento de servidores.</li><li><strong>Manejadores de paquetes </strong>.- Como npm y bower , que facilitan la instalación de librerías en los proyectos.</li></ul><h3>¿Cómo llegó Android ?</h3><p>Sinceramente siempre sentí la curiosidad sobre programar en varias plataformas, me llamaba mucho la atención ver que habían personas que podían programar especialmente para celulares, televisores, etc ; desde mi punto de vista era como trascender de lo habitual.</p><p>Un día recibí una propuesta de trabajo en donde me proponían aprender sobre esto y dije : ¿Por qué no? … Este fué el inicio de mi aventura con el desarrollo Android 😊.</p><p>Cuando acepté la propuesta , pensé : “OK, pero ¿Qué implica realmente desarrollar para Android ? ” .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*pepmrNR_YPMRYbBFsNpB1A.png" /></figure><p>Para empezar a desarrollar aplicaciones mobile nativas en Android , es necesario derribar muchas paredes de conceptos nuevos ; el camino no es fácil , pero si encuentras una muy buena motivación para seguir adelante y tienes muchas ganas de aprender , sería bueno que tomes en cuenta los siguientes pasos(no olvides llevar estos conceptos de la mano con la <a href="https://developer.android.com/"><strong><em>documentación oficial</em></strong></a> que nos ofrece Android) :</p><h4>Programación Orientada a Objetos (POO):</h4><p>Digo que este es el paso 0 , porque muchas personas asumen que es algo que un@ ya debería saber , sin embargo para mi (con 6 meses programando en ese entonces), fué algo nuevo . Cuando estuve buscando en internet sobre POO me topé con lecturas muy interesantes, que tenían muchos conceptos como : Clases, herencia , encapsulamiento, cohesión, abstracción, polimorfismo y acoplamiento (sabía superficialmente de los 3 primeros ,de abstracción y de los 3 restantes no era consciente de que existían); quedé en shock con el mundo de conceptos nuevos que encontré.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*v-6bIbLwU8ZS41oGKg1ZBQ.gif" /></figure><p>Todos esos conceptos trascienden del lenguaje de programación; eso está bien , pero para este propósito era importante ver que esos conceptos se orienten a Java; por lo que recomiendo muchísimo este curso:</p><ul><li><a href="https://www.udacity.com/course/object-oriented-programming-in-java--ud283"><strong>Object Oriented Programming in Java</strong></a><strong> [by Google]</strong> de Udacity.</li></ul><p>Este curso es mucho más enfocado y tiene lo necesario para entrar en el siguiente paso.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IhvhQct7dkxBn5Ko" /><figcaption>Photo by <a href="https://unsplash.com/@lindsayhenwood?utm_source=medium&amp;utm_medium=referral">Lindsay Henwood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Java + Android Studio :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*EyL0-D2uOpqwB_HWOxdN1w.png" /></figure><p>Antes de entrar a Kotlin , es importante consolidar los conocimientos en Java ; si bien es cierto Kotlin ya es el lenguaje oficial del desarrollo Android; no podemos olvidar que Java aún sigue siendo parte de Android, además de que gran parte de los tutoriales se encuentran en Java .</p><ul><li><a href="https://www.udacity.com/course/android-basics-user-interface--ud834"><strong>Android Basics: User Interface</strong></a> [by Google] de Udacity.</li><li><a href="https://www.udacity.com/course/android-basics-user-input--ud836"><strong>Android Basics: User Input</strong></a><strong> </strong>[by Google] de Udacity.</li><li><a href="https://www.udacity.com/course/android-basics-multiscreen-apps--ud839"><strong>Android Basics: Multiscreen Apps</strong></a> [by Google] de Udacity.</li><li><a href="https://www.udacity.com/course/android-basics-networking--ud843"><strong>Android Basics: Networking</strong></a> [by Google] de Udacity.</li><li><a href="https://www.udacity.com/course/android-basics-data-storage--ud845"><strong>Android Basics: Data Storage</strong></a> [by Google] de Udacity.</li></ul><p>Todo esto forma parte del curso<strong> Android Development for Beginners; </strong>una vez familiarizad@ con estos conceptos , lo ideal sería seguir con el fascinante mundo de Kotlin .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*WLNZLS4nb3XOW9maLQLD1g.gif" /></figure><h4>Android Studio + Kotlin :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*3T_W1dMbDAYkClPejRAUIw.png" /></figure><p>Como ya lo mencioné antes Kotlin es el lenguaje oficial de Android , cuando vi por primera vez Kotlin me dió la ligera impresión de que era algo así como JavaScript y Java juntos en una licuadora (obviamente es mucho más que eso). A continuación detallo un par de características más resaltantes :</p><ul><li><strong>Es muy sencillo y pragmático</strong> .- ¿Qué quiere decir esto?Pues , es un lenguaje bastante práctico , no es tan fuertemente tipado como Java y tiene una curva de aprendizaje mucho más ligera , a diferencia de otros lenguajes de programación.</li><li><strong>Es Interoperable al 100% con Java .- </strong>Ideal para migrar aplicaciones antiguas.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0_3fqZx6UL2AN11jMxtZgA.gif" /></figure><p>Suena como un lenguaje de programación muy amigable ; para entenderlo mucho mejor sería una buena idea revisar la documentación oficial :</p><ul><li><a href="https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt">Kotlin Programming Language</a> — Documentación oficial.</li></ul><p>y el siguiente curso:</p><ul><li><a href="https://www.udacity.com/course/kotlin-bootcamp-for-programmers--ud9011">Kotlin Bootcamp for Android Developers</a> [bye Google] de Udacity.</li></ul><h4>La comunidad de Android es importante :</h4><p>Cuando estamos adentrándonos en un mundo nuevo , es importante ser y sentirse parte de él; por lo que siempre es bueno mantenerse al tanto de las últimas actualizaciones de la comunidad, seguir a los máximos referentes, para que poco a poco nos vayamos familiarizando con el entorno y nos vayamos sintiendo parte de él .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Vu9isMmFHq6Jwws1-9shGw.jpeg" /></figure><ul><li><a href="https://androidweekly.net/"><strong>Android weekly</strong></a> .-Revista semanal, te inscribes y te llega un correo cada semana con las últimas actualizaciones 😊.</li><li><a href="https://www.androiddevdigest.com/"><strong>AndroidDevDiges</strong></a><strong>t</strong> .-Revista semanal; también llegan muy buenas actualizaciones de este sitio.</li><li><strong>Medios sociales</strong> .- Si eres de usar redes sociales como twitter sería bueno que empieces a seguir a referentes como <a href="https://twitter.com/riggaroo?source=user_profile----------------------------">Rebecca Franks</a> ,<a href="https://twitter.com/FMuntenescu"> Florina Montescue </a>, las plataformas oficiales : <a href="https://twitter.com/AndroidDev">Android Developers </a>, <a href="https://twitter.com/androidstudio">Android Studio</a>,<a href="https://twitter.com/googledevs"> Google Developers</a>, por citar algunas . Todas nos mantienen actualizados .</li><li><strong>Canales en Youtube</strong> .- <a href="https://www.youtube.com/channel/UCMEmNnHT69aZuaOrE-dF6ug">Android Dialogs </a>y <a href="https://www.youtube.com/channel/UCVHFbqXqoYvEWM1Ddxl0QDg">Android Developers</a> son unas muy buenas opciones para empezar 😄.</li></ul><p>No existe una única fórmula ni el momento perfecto para decidir entrar en el mundo Android, pero si tienes el empuje necesario y le pones todas las ganas garantizo que es una experiencia única y muy reconfortante ✌️ 💚 ✌️ 😊, la verdad es que todos tenemos distintas formas de aprender , descubre la tuya y habrás trazado tu camino perfecto en el mundo de la programación ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b067348a31d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/descubriendo-el-mundo-android-9b067348a31d">Descubriendo el mundo Android 💚</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Qué es y qué no es Android Jetpack]]></title>
            <link>https://medium.com/orbismobile/qu%C3%A9-es-y-qu%C3%A9-no-es-android-jetpack-1248d1f36670?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/1248d1f36670</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-jetpack]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[architecture-components]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Wed, 27 Jun 2018 23:23:18 GMT</pubDate>
            <atom:updated>2018-06-27T23:30:12.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zSRBNJ58FJzyw-T2G6rqw.png" /></figure><p>El Google I/O de este año trajo consigo muchas sorpresas para todos los productos de la gran G, sea para Google Assistant, Google Maps, Android Things, etc; pero de entre todas las novedades, más aún en el mundo Android, Google nos trajo <strong><em>Android Jetpack</em></strong> de quien les vengo a hablar hoy.</p><p>Recuerdo que estaba siguiendo por streaming el Google I/O, cuando comenzaron a hablar de las novedades en Android. Me paré unos segundos a la cocina a tomar un vaso con agua cuando escuche hablar Android Jetpack, así que volví a mi asiento rápidamente para ver de qué trataba y la primera imagen con la que me topé fue esta:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPe93-NWXAili2anuyel4A.png" /><figcaption>Fuente: Android Developers Blog</figcaption></figure><p>Y por alguna razón lo primero que pensé fue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdZ49PHvShu7pEP7Kx6nUg.png" /></figure><p>Y comenzaron comentarios en la oficina como: ¡Ey mira el nuevo Storyboard de Android!, ¡Ahora Android tendrá su Storyboard como iOS!, etc.</p><p>Pero la verdad es que <strong><em>Android Jetpack </em></strong>no es el nuevo “Storyboard” de la plataforma Android. Entonces, ¿Qué es Android Jetpack?.</p><blockquote>Android Jetpack ayuda a acelerar el desarrollo de Android con componentes, herramientas y guías que eliminan las tareas repetitivas, permitiendo crear de forma más rápida y sencilla aplicaciones de alta calidad y testeables. | Android Developer Page</blockquote><p>Hasta esta parte entendemos que Android Jetpack no es ningún <em>Storyboard</em>, no es ningún plugin para Android Studio que te haga aparecer mágicamente un <em>Storyboard, </em>ni nada que incluya la palabra <em>Storyboard. </em>Es mucho más, es una guía arquitectural apoyada por nuevas librerías, herramientas como Android Studio y conceptos que nos ayudan a mejorar el desarrollo en Android. Entonces podemos afirmar que Android Jetpack es:</p><blockquote>Es una guía arquitectónica, soportada por un conjunto de librerías y herramientas en cuatro áreas clave del Desarrollo de Android.</blockquote><p>Las cuatro áreas clave que soportan a Android Jetpack son: Arquitectura, Interfaz de Usuario, Fundamento y Comportamiento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FB931aBGoALv3OLY5LSRGg.png" /><figcaption>Áreas de Android Jetpack</figcaption></figure><p>Cada área tiene sus propias características, componentes, librerías y definiciones. Algunos ya existentes desde mucho antes en el mundo de Android, como las Notificaciones, Fragmentos, AppCompat, Permisos, Media, etc. Android Jetpack sólo los ha organizado y separado por áreas, ayudándonos a tener un mejor panorama de todo el mundo Android, al mismo tiempo que en algunos casos, se ha agregado herramientas y librerías que ayudan su implementación que en años anteriores suponía el uso de mucho código boilerplate.</p><p>Esta <em>“colección de librerías”,</em> son individualmente adoptables y construidas para trabajar juntas mientras aprovechan todas la potencia de Kotlin, lo hace aún más productivo.</p><p>En este post hablaremos de los nuevos componentes que Android Jetpack trae a cada área (las cuatro mencionadas anteriormente) para potenciarlas y/o mejorarlas. Dado que si hablamos de cada componente existente como tal quizás necesite al menos unos 100 posts más para poder terminar 😆.</p><h3>Arquitectura (Architecture)</h3><p>Google nos había dado un adelanto de esto en el anterior Google I/O 2017, donde presentó la Arquitectura de Componentes. Tal como su nombre menciona, una arquitectura base para todas nuestras aplicaciones Android bajo un patrón MVVM.</p><p>Hace unas semanas, mi amigo <a href="https://medium.com/u/62ef5f2c3253">Carlos Leonardo Camilo Vargas Huamán</a> dio un meetup acerca de esta arquitectura donde la explica al detalle.</p><p><a href="https://medium.com/orbismobile/arquitectura-de-componentes-en-android-d244d329be5a">Arquitectura de Componentes en Android</a></p><p>Y como mencioné antes, Android Jetpack está dando mejoras a cada área de Android y una de ellas es a su arquitectura, sumando tres nuevos componentes: Navigation, Pagging y Workmanager.</p><h4>Navigation</h4><p>Este nuevo componente nos permite estructurar fácilmente nuestra interfaz de usuario, creando flujos más limpios al momento de hacer nuestra aplicación. Al mismo tiempo de tener compatibilidad con los Fragmentos, facilita enormemente la tarea de los clásicos FragmentTransactions y el control que este conlleva como el <strong><em>attach/detach</em></strong> de estos. Sumado a que Android Studio nos dará una herramienta visual que ayudará a ver el flujo que estamos construyendo y todos los eventos necesarios para estos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPe93-NWXAili2anuyel4A.png" /><figcaption>Ahora si esta imagen tiene sentido.</figcaption></figure><h4>Pagging</h4><p>La Librería de paginación facilita la carga de datos dentro de un RecyclerView, teniendo la data sesgada y progresiva conforme sea requerida. Podemos cargar datos para la paginación desde el almacenamiento local, red o ambos. La librería de Pagging permite el trabajo conjunto con Room, LiveData y RxJava, siendo libre de escoger al momento de su implementación sobre una aplicación que ya tengamos construida.</p><h4>Workmanager</h4><p>WorkManager es una nueva y potente librería que proporciona un gran apoyo para trabajos en segundo plano, pero a diferencia de los clásicos Asyntask o Executors; Workmanager se basa en restricciones que necesita una tarea para ser garantizada con éxito al momento de cumplirla. Tomando por ejemplo si deseamos subir una foto al servidor pero deseamos que solamente se realice esta tarea si el celular esta conectado a corriente y conectado a internet. Podemos hacer esto con muchas líneas de código, validaciones y horas de codeo o, crear nuestro Workmanager 😄.</p><h3>Interfaz de Usuario (UI)</h3><p>En la interfaz de usuario ha habido cambios interesantes para Wear OS (Android Wear) y Android Auto, al mismo tiempo que APIs como Pallette se siguen actualizando para su compatibilidad con las demás versiones de android.</p><p>Entre estas librerías tenemos a <strong><em>EmojiCompat</em></strong> que nos permite tener una compatibilidad de Emojis entre cada plataforma y así evitar los clásicos “☐” cuando tratamos de compartir un emoji.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yjlG0EHwxXTOUrWv8ku8sA.png" /></figure><p>Teniendo la <em>fuente</em> de traducción para los Emojis como soporte, esta librería nos permite tener la compatibilidad para cada carácter buscado e interpretarlo como el Emoji correcto que le corresponda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lL8V5n9LDKYW6JCDz1Xy-Q.png" /></figure><h3>Fundamento (Foundation)</h3><p>En este caso, la traducción es muy literal, en realidad sería Base o Cimientos, dado que esta área de Jetpack es la encargada de dar “asistencia” a todas las demás áreas de Android Jetpack como tal.</p><p>Los componentes de <strong><em>“Foundation”</em></strong> proporcionan capacidades principales del Sistema, <em>“Kotlin extensions”</em>, soporte para Multidex y pruebas automatizadas.</p><p>En el caso de las capacidades del sistema, podemos hablar de la librería AppCompat que nos provee distintos paquetes/módulos para poder dar soporte a las distintas versiones de Android. Jetpack sin embargo trajo cambios para este tipo de librerías, y uno de los cambios fue unificar la estructura de paquetes de las librerías de soporte bajo el nombre de AndroidX.</p><h4>AndroidX</h4><p>Todos aquellos que somos programadores Android, somos conscientes de todo el lío que es la compatibilidad con versiones anteriores de las librerías de soporte como: v4, v7, v13, v8, etc, etc. ¿Entonces cómo Google está arreglando esto?</p><p>Jetpack está implementando una nueva estructura para esclarecer qué paquetes se incluyen con el sistema operativo Android y cuáles con el APK de la aplicación. En el futuro, la jerarquía de paquetes android.* se reservará para los paquetes Android que se envíen con el sistema operativo; lo demás paquetes se publicarán bajo la nueva jerarquía de paquetes androidx.*:</p><p>Entre los cambios tenemos:</p><p><strong><em>Refactorización de Paquetes Java a androidx:</em></strong></p><pre>androidx.&lt;feature&gt;.ClassName</pre><p><strong><em>Nomenglaturas Maven más consistentes:</em></strong></p><pre>androidx.&lt;feature&gt;:&lt;feature&gt;-&lt;sub-feature&gt;</pre><p>Con lo anterior dicho, adiós -v4, -v7- v13, etc etc etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuPb2gCv2zyaxZa-Kluwjw.png" /><figcaption>Fuente: Medium — Mindorks</figcaption></figure><h4>Material Design 2.0</h4><p>Material Design fue presentado en el 2014 junto a Android 5.0 Lollipop y se considera un hito en la historia Android, pues rompía con todo los esquemas de diseño hasta entonces. Para quienes no lo conozcan, Material Design es el nombre que recibe el diseño de Google desarrollado por Matías Duarte. Se basa en superficies planas, con elementos muy coloridos y niveles de capas diferenciados. Google apostó fuerte por Material Design, no solo en Android sino en wearables, televisores, ordenadores y páginas web. Un mismo diseño fácil de identificar y asociar con la compañía.</p><p>Sin embargo desde ya hace unos meses, Google ha ido liberando de a pocos las guías de su nueva versión de Material Desing, muchos lo han podido comprobar en la nueva interfaz de Gmail, en su nueva aplicación Tareas, y todas bajo esta nueva línea gráfica de Material 2.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMdI2v-OZIHfD79Kjo9BLQ.png" /><figcaption>Fuente: Medium — Mindorks</figcaption></figure><p>Y todos estos nuevos componentes se irán actualizando en nuestra librerías de soporte.</p><h4>KTX</h4><p>Desde que se lanzó Kotlin para el desarrollo de Android, Google fue consciente que tenía un par de cosas por resolver con respecto a él. Si bien en sí el lenguaje ya era un revolución para todos aquellos que venían del mundo Java, habían algunas cosas por limar y ordenar.</p><p>Es así que el 5 de Febrero de este año Google lanzó Android KTX, un conjunto de extensiones diseñadas para escribir código Kotlin más conciso, idiomático y agradable, aprovechando las características de Kotlin tales como funciones de extensión, lambdas, parámetros nombrados y valores por defecto de los parámetros.</p><p>Entonces es así que este conjunto de extensiones Kotlin forma parte de la familia Android Jetpack, optimizando las APIs de las plataformas Jetpack y Android para el uso de Kotlin.</p><p>Ojo, Android KTX no añade ninguna característica nueva a las APIs existentes de Android, simplemente hace que Kotlin sea más simple y agradable de lo que ya es 😊.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPF16EZOkpNpUIe5-CFfzQ.png" /><figcaption>Fuente: Android Developers Blog</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99dsM7RAoI2Z8VXBtopS5g.png" /><figcaption>Fuente: Android Developers Blog</figcaption></figure><h3>Comportamiento (Behavior)</h3><p>Aquí encontraremos componentes como las Notificaciones (tanto para Móviles como Werables), Permisos (introducidos desde Android 6), el api para compartir (Share) links, textos, etc; Media, Dowload Manager, etc.</p><p>Sin embargo el reciente agregado con Android Jetpack es Slices.</p><h4>Slices</h4><p>Son plantillas para la UI que pueden mostrar contenido sofisticado, dinámico e interactivo de tu aplicación con la <em>aplicación de búsqueda de Google</em> y, posteriormente desde otros lugares como el <strong><em>Asistente de Google</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jPTMVdVIgLMzMpciLyV4Q.png" /><figcaption>Fuente: Google I/O 2018</figcaption></figure><p>Dicho de otra forma, si tu aplicación contiene tareas y/o almacenamiento con fotografías/imágenes, interacción con mapas, pide un auto, da recordatorios, compra tickets de cine, etc; podrás hacer que interactúe con la aplicación de búsquedas y el asistente de Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cjyz-CSjetMp7KtoiV3QlA.gif" /><figcaption>Si lo sé, es hermoso :’ ) 😭</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*rp8SAiYbWae2H5s6Gm_DOA.png" /><figcaption>Fuente: Medium — Mark Dappollone</figcaption></figure><p>Ahora nuestra aplicación también podrá tener estos “accesos directos” con los productos de Google para hacer nuestras aplicaciones aún más interactivas con el ecosistema Google.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*1j3_m7sDxOj0UR1UqEDhgA.png" /></figure><p>La compatibilidad con Slices está integrada en Android Jetpack y puede extenderse hasta Android 4.4, llegando aproximadamente al 95% de todos los usuarios de Android 🎉🎉🎉🎉.</p><p>Bueno he tratado de hacer un mega resumen de que abarca Android Jetpack, aclarar que no es un Storyboard y hablar de sus cuatro áreas de desarrollo en Android. Aún sigue creciendo y añadiendo más librerías y componentes que nos ayudarán a mejorar nuestro desarrollo en Android. Hasta entonces . . .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*wIP9lb0MUGe2CBHiRy1oTA.gif" /></figure><h3>Referencias</h3><ul><li><a href="https://android-developers.googleblog.com/2018/05/google-io-2018-whats-new-in-android.html">Google I/O 2018: What&#39;s new in Android</a></li><li><a href="https://android.jlelse.eu/jetpack-series-1-androidx-a-headache-for-a-better-package-structure-62c3608596fd">Jetpack series: 1 — androidx.*, a headache for a better package structure</a></li><li><a href="https://developer.android.com/jetpack/">Android Jetpack | Android Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1248d1f36670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/qu%C3%A9-es-y-qu%C3%A9-no-es-android-jetpack-1248d1f36670">Qué es y qué no es Android Jetpack</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lo que nos dejo el WWDC 2018]]></title>
            <link>https://medium.com/orbismobile/lo-que-nos-dejo-el-wwdc-2018-e383e1fadf96?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/e383e1fadf96</guid>
            <dc:creator><![CDATA[Erik Flores]]></dc:creator>
            <pubDate>Wed, 27 Jun 2018 23:19:35 GMT</pubDate>
            <atom:updated>2018-06-28T09:41:34.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjSTa4Lav4ntfJrF_TWoGw.jpeg" /></figure><p>El WWDC es el evento más importante en el mundo de desarrollo Apple, por ende, es el evento donde al empresa muestra el camino que tomara sus diferentes plataformas de ahora en adelante, bajo esta premisa, ya es una costumbre que muestre las nuevas versiones de iOS, watchOS, macOS y tvOS</p><h3><strong>iOS 12</strong></h3><p>Este año, las mejoras en iOS van enfocadas en temas de <em>performance</em>, es muy interesante que apple aya tomado esta decision, después de que aceptaron que tomaban desiciones arbitrarias sobre como manejaban el <em>performance</em> de las baterías del iPhone. Lo bueno es que iOS agrego nuevas funcionalidades para saber en que estamos consumiendo nuestra batería. Otro buen punto de este enfoque, es que iOS 12 podrá ser instalado desde un iPhone 5s con el plus de mejorar su <em>performace (</em>tratando de romper el mito que con cada actualización el dispositivo se pone más lento), lo que más me gusta de todo esto es que apple le siga dando soporte y mejoras a un dispositivo que se lanzo hace 5 años.</p><h4>Memoji</h4><p>Al parecer expresarse con emojis no es suficiente, es por ese motivo, que muchas empresas han lanzados diferentes propuestas donde se busca personalizar los emojis. Apple no se quizo quedar atrás y lanzo los memojis, bajo mi punto de vista es un bueno uso que le han dado a la tecnología que desarrollaron para la cámara frontal del iPhone X y a su framework de Realidad Aumentada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*AAuGaR9SBwNn6Wvz4W5gMg.png" /><figcaption>Bitmoji nunca te cambiaré</figcaption></figure><h4>FaceTime</h4><p>Quizas nadie se lo esperaba, pero ahora FaceTime soporta una video llamada de hasta 32 personas, quizás muchos puedan decir ¿para qué?, pero si hacemos incapie en que apple vende grandes cantidades de iPhones cada año y que tienen una cuota de mercado regular en laptops y son casi la mejor opción a lo que tablets se refiere y encima que FaceTime viene preinstalado, solo muestra que apple sabe lo que tiene y que trata de dar siempre una buena experiencia con sus productos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*sjf4FBnYR16qdO-oyqXIdQ.png" /><figcaption>32 personas ! 🤔</figcaption></figure><h4>ARKit 2</h4><p>Me impresiona todo el esfuerzo que Apple le esta dando a la realidad aumentada, ya van dos años seguidos donde muestran avances de AR en sus <em>Keynote</em> y a eso le agregamos que se creo una sección de AR en la AppStore.<br>Este año ARKit agrego mejoras en <em>tracking</em> de figuras 2D, 3D y quizás una de las que mas me gusto, la posibilidad de crear un entorno de realidad aumentada compartido, el cuál esta mas orientada a la creación de juegos usando AR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*glVLdt1galTeIwf2m2f6Bw.png" /><figcaption>Me gustaria que juegos como shadowmatic adopten esta tipo de idea de juegos colaborativo con AR.</figcaption></figure><h4>Productividad</h4><p>Me gusta que Apple no solo se enfoque en crear nuevas funcionalidades para vender sus iPhones sino también en como los usamos, mostrandonos en que apps consumimos más tiempo y dandonos la opción de bloquearnos la pantalla después de un uso intenso de la app que mas tiempo nos esta quitando, la verdad me gusto mucho esta última parte, a eso debemos mencionar que si tenemos la opción de Family Sharing podremos controlar el tiempo que se gasta en ciertas apps en los diferentes miembros de la familia, esto esta muy bien pensado para los niños especialmente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*_oiodEyUGloBodn8i3em4Q.png" /><figcaption>Te imaginas que aparesca esa pantalla cuando estes apunto de pasar un nivel importante en tu juego</figcaption></figure><h4>Notificaciones</h4><p>Las notificaciones recibieron las mejoras que todos los usuarios pedían, las tan esperadas notificaciones agrupadas, porque creeanmé no es chevere recibir 50 notificaciones de mensajes y tener que estar haciendo scroll para ver notificaciones que llegaron previamente. Usando el ejemplo anterior de las 50 notificaciones, apple también agrego mejoras para el control de las notificaciones desde el <em>notification center</em> para tener un mejor control de las misma cuando te estén llegando notificaciones de manera agresiva y tu estes viendo un video o estes proyectando la pantalla de tu iPhone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*KzqV_2q89wivkmJ2KhknQQ.png" /><figcaption>Yo: Gracias por notificaciones agrupadas, Apple: De nada Erik, espero que compres el nuevo iphone el proximo año.</figcaption></figure><h3>MacOS Mojave</h3><p>Mojave trae cosas buenas como el:<br>- <strong>Dark Mode</strong>, para aquellos que prefieran las interfaces oscuras.<br>- <strong>Stacks</strong>, para poder organizar de una manera mas rápida nuestro escritorio.<br>- <strong>Continuity Camera</strong>, en caso necesitamos un foto en uno de nuestros documentos de Pages o Keynote, nos da la posibilidad de obtenerlos mediante el iPhone. (Fue muy interesante la verdad, pero no se cuantas veces lo usare).</p><p>Pero quizás el mejor anuncio y mas interesante que se hizo para Mojave, es que vamos a poder usar UIKit en macOS (algo que era conocido como proyecto Marzipan), el hecho de que UIKit podrá ser usado en macOS, esto significa que todas las aplicaciones que fueran desarrolladas para iOS podrán ser instaladas en macOS 🤩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*AvYyvihXffAVlSGby_GP6A.png" /><figcaption>El dark mode tiene la versión del icono de basurero mas sexy de la historia</figcaption></figure><h3>watchOS 5</h3><p>Este año watchOS recibió mejoras como:<br>- Una aplicación <em>standalone</em> para escuchar <em>podcasts</em><br>- La posibilidad de retar a tu amigos para ver quien hace mas ejercicio<br>- Una app de Walkie-Talkie (curioso por cierto)<br>- Y la posibilidad de ver paginas web en el reloj, la verdad que es un gran esfuerzo bajo mi punto de vista porque almenos ya no te aperecera el mensaje “por favor miralo en el iPhone”</p><p>Estas mejoras me hacen pensar que apple watch en un tiempo va a perder gran parte de su dependencia del iPhone y podremos salir sin nuestro iPhone sin ningún problema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*qlZWN6N_pdd8aRj352vHOQ.png" /><figcaption>Que dia ver un apple watch circular ?</figcaption></figure><h3>Xcode 10</h3><p>Aparte de traer las ultimas versiones de los diferentes APIs de las diferentes plataformas y Swift 4.2, se han agregado:<br>- Una mejor integración con git, ahora podremos ver de una forma mas clara en que parte del archivo se agrego código y quien lo agrego, además soporte a las plataformas de git mas usadas (github, bitbucket, gitlab) y la posibilidad de hacer pull con rebase.<br>- ¡ Edición de lineas de código usando multicursores !<br>- Ahora podremos ejecutar código paso a paso e ir agregando lineas de código en caliente usando playground, sin necesidad de volver hacer build y volver a correr todo de nuevo, <a href="https://developer.apple.com/videos/play/wwdc2018/402/">vale la pena verlo con tus propios ojos</a>.<br>Para ver mas detalles sobre las nuevas funcionalidades te recomiendo que veas el <a href="https://developer.apple.com/videos/play/wwdc2018/102/">Platform State of the Union</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Heip5BP_u441h3BQ_pasQ.png" /><figcaption>xcode 🖤</figcaption></figure><h3>Apple Design Awards</h3><p>El apple design awards es como el oscars del mundo apple, este año toco ver calculadoras, traductores en realtime, agendas y juegos, pero con un toque diferenciador que hagen que destaquen del resto de las apps, este año mi favorito fue Playdead’s INSIDE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fw8nfl7pWfCAsoDgeYcVBQ.png" /><figcaption>Playdead’s INSIDE 🤯</figcaption></figure><h3>Frameworks</h3><p>Los frameworks estrellas este año fueron ARKit, Core ML y SiriKit</p><h4>ARKit</h4><p>Entre las mejoras más interesantes, es que ahora ARKit ya trabaja mejor el tema de las texturas, mejora el WorldTracking para el reconocimientos de objetos en el mundo real, el reconocimientos de objetos en movimientos y la presentación del formato usdz para la previsualización de objetos en 3D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*UBqkbgdx6diOr2EQeSxmXw.jpeg" /><figcaption>Lo mas interesante de los archivos USDZ es que podran ser generados mediante xcrun</figcaption></figure><h4>Core ML</h4><p>Otra tópico a la que apple le esta poniendo mucho esfuerzo es al de Machine Learning, en el 2017 presentaron la primera version de este framework, el framework ayuda mucho a la fácil implementación de modelos de machine learning, el punto es que para la creación de modelos había que tener un <em>background</em> de por medio, este año Apple quizo romper esta brecha y hacernos la vida mas fácil con la creación de Create ML el cual nos permite crear modelos ligeros de una manera fácil via playground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*GhoSdJzqKj7-KSxZoUYJUQ.png" /><figcaption>Create ML es absurdamente genial</figcaption></figure><h4>SiriKit</h4><p>Todos estamos expectantes que iba hacer apple con su Siri, ya que para ser honestos esta quedando muy atrás a comparación de sus competidores. Este año Siri no mejoro tanto como para ser el nuevo Ultron, pero si agregaron una nueva funcionalidad llamada Siri Shorcut que nos ayuda a grabar flujos de nuestras apps y asociarlas a un comando de voz via Siri, esto viene de la mano de la nueva app llamada Shortcut que basicamente es Workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*VkCkNUBapsIm4OqKrboGoQ.png" /><figcaption>hello workflow</figcaption></figure><h4>Nuevos mienbros</h4><p>Apple lanzo nuevos frameworks como:<br>- <strong>MapKitJS, </strong>apple maps en la web<br>- <strong>MusicKitJS</strong>: apple music para la web<br>- <strong>Authentications Services</strong>: para poder autocompletar claves de nuestras cuentas.<br>- <strong>Network</strong>: para poder interactuar directamente con protocolos como TLS, TCP y UDP.<br>- <strong>Natural Language</strong>: Reconocimiento de texto en lenguaje natural.<br>- <strong>TVUIKit</strong>: para tener un <em>standar</em> de UI entre las apps nativas para el apple TV.</p><h3>Videos que recomiendo</h3><p>Una de las cosas que mas me gusta del WWDC es que deja una gran cantidad de conocimiento para aprender, entre los videos que podria recomendar serián:</p><ul><li><a href="https://developer.apple.com/videos/play/wwdc2018/408/">Building Faster in Xcode</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/303/">Automating App Store Connect</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/211/">Introduction to Siri Shortcuts</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/602/">What’s New in ARKit 2</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/412/">Advanced Debugging with Xcode and LLDB</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2018/102/">Platform State of the Union</a></li></ul><p>Recuerden que hay muchos mas charlas en la siguiente <a href="https://developer.apple.com/videos/wwdc2018/">web</a> y caso necesiten un tema en especial y no quieren ir buscando en todos los videos pueden usar <a href="https://asciiwwdc.com/">ASCIIwwdc</a>.</p><p><a href="https://medium.com/u/aef35aee355c">Erik Flores</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e383e1fadf96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/lo-que-nos-dejo-el-wwdc-2018-e383e1fadf96">Lo que nos dejo el WWDC 2018</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navegando entre fragmentos sin perder su estado | Android]]></title>
            <link>https://medium.com/orbismobile/navegando-entre-fragmentos-sin-perder-su-estado-android-febc7c2b16a7?source=rss----5e49fab6609---4</link>
            <guid isPermaLink="false">https://medium.com/p/febc7c2b16a7</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[fragments]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Carlo Huamán]]></dc:creator>
            <pubDate>Mon, 04 Jun 2018 18:15:34 GMT</pubDate>
            <atom:updated>2018-06-04T18:15:34.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7YHInz8DRnRe5ZMFZSnuQ.jpeg" /><figcaption>vía CNN | Anisha Shah</figcaption></figure><p>Más de una vez me he topado con el dilema de: ¿Cómo debo cambiar entre fragmentos al implementar Tabs o un Bottom navigation en una Actividad?, hay muchas formas de hacerlo en realidad, pero siempre esta la duda. ¿Cómo?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1PRfJv5tXRive%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1PRfJv5tXRive%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1PRfJv5tXRive%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="235" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b434ffba59bf8b35023b516f54c4b87/href">https://medium.com/media/0b434ffba59bf8b35023b516f54c4b87/href</a></iframe><p>En realidad esto no es muy complicado, basta con usar un <strong><em>replace</em></strong> y ¡Listo! ¿no?. Creo que todos alguna vez, cuando hemos querido cambiar entre fragmentos hemos hecho algo así:</p><pre><strong>val </strong>transaction = <em>supportFragmentManager</em>.beginTransaction()<br>transaction.replace(R.id.<em>container</em>, fragment)<br>transaction.commit()</pre><p>Y de hecho esta bien, funciona. Y si lo lleváramos a una simple aplicación, tendriamos algo asi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*5FUQWXSd4TmN574SjGZclQ.gif" /></figure><p>Pues todo bien hasta ahí mientras avancemos de un fragmento a otro, pero ¿Y si quisiera regresar al fragmento anterior?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*a5dLhwfvnt1nZX_puu-58A.gif" /><figcaption>Ups!</figcaption></figure><p>¿Qué sucedió?, ¿Porqué no regresé al anterior fragmento? — Al presionar el botón <em>atrás (back) </em>de nuestro dispositivo, accionamos un evento llamado <strong><em>onBackPressed. </em></strong>Este evento te permite “retroceder/navegar”, entre las actividades que hallas agregado a la pila de la aplicación (task).</p><p>Hagamos una pausa aquí para entender primero que sucede con la pila de una aplicación.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*M1ukvU3L12BNG19XbkrrAg.png" /><figcaption>BackStack Diagram — vía Android Developers</figcaption></figure><p>Como podemos ver en la imagen anterior, primero sólo tenemos un <strong><em>Activty 1</em></strong>, como si hubiéramos creado una aplicación que tenga Menú Principal (<strong><em>Activity 1</em></strong>), luego nos mande a un resultado de búsquedas (<strong><em>Activity 2</em></strong>), y al picar en un resultado, nos dirijamos a un detalle de este resultado(<strong><em>Activity 3</em></strong>).</p><p>Hemos creado un flujo de <strong><em>Activty 1 → Activity 2 → Activity 3, </em></strong>también llamado pila (task) de nuestra aplicación. Si volvemos atrás por medio del evento <strong><em>onBackPressed</em></strong>, el <strong><em>Activity 3</em></strong> es cerrado/terminado, y la aplicación trae al último elemento de la pila, en este caso el <strong><em>Activity 2.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*qqpWhP3MKz_oESpPEi0-bg.gif" /><figcaption>BackStack Activities | vía YouTube Android Developers</figcaption></figure><p>Todo bien, pero ¿Y con los fragmentos que sucede?. Los fragmentos también pueden ser agregados a la pila agregando una línea a nuestro código inicial.</p><pre><strong>val </strong>transaction = <em>supportFragmentManager</em>.beginTransaction()<br>transaction.replace(R.id.<em>container</em>, fragment)<br><strong><em>transaction.addToBackStack(</em></strong><em>null</em><strong><em>)</em></strong><br>transaction.commit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*0821l1xC9m3F1Tczh-A5Ww.gif" /><figcaption>BackStack Fragments | vía YouTube Android Developers</figcaption></figure><p>Entonces, si mis fragmentos ya son agregados a la pila de la aplicación ya puedo navegar entre ellos ¿verdad? Veamos como quedaría nuestra aplicación ahora.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*ltj8IW9WiIi8t3S3llzeTg.gif" /><figcaption>Yeah!</figcaption></figure><p>Entonces, ya puedo navegar entre fragmentos 🙌🏻💪🏽🤘🏽, sin embargo, ¿Qué sucede detrás del replace() que usamos para cambiar los fragmentos?; veamos que nos dice la documentación:</p><blockquote>Reemplaza un fragmento existente que halla sido agregado a un contenedor. Esto es esencialmente lo mismo que llamar a un <strong>remove(Fragment)</strong> para todos los fragmentos que fueron agregados con el mismo <strong>containerViewId</strong> y luego un <strong>add(int, Fragment, String) </strong>con los mismos argumentos dados aquí. (<a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction#replace">developer.android.com</a>)</blockquote><p>Entonces, un <strong>replace() </strong>reemplaza (valga la redundancia 😆) un fragmento existente en el contenedor que estemos trabajando. Para lograr esto, invoca dos funciones de forma interna: <strong>remove()</strong> y <strong>add(); </strong>¿Qué dice la documentación acerca de un<strong> remove()</strong>?:</p><blockquote>Elimina un fragmento existente. Si se agregó a un contenedor, su vista también se elimina de ese contenedor. <a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction#remove">(developer.android.com</a>)</blockquote><p>¿Por qué es importante saber todo esto si mi aplicación ya esta funcionando?. Hagámonos las siguientes preguntas:</p><ul><li>¿Qué pasaría si en lugar de tener un pequeño texto en mi fragmento tengo un ListView o RecyclerView?</li><li>¿Qué pasaría si cargo datos de un servicio externo (REST | GraphQL)?</li><li>¿Qué pasaría si tengo un ScrollView del cual quiero mantener su última posición?</li><li>¿Si sólo voy a manejar entre 3 a 4 fragmentos, tengo que estar recreándolos todos a cada momento que cambio entre ellos mismos?</li></ul><p>Se que hay muchos tutoriales que nos muestran que jugando con el <strong><em>onBackStackChanged() </em></strong>se puede manipular el cambio entre fragmentos, pero personalmente es una forma que no me gusta usar, más aún si quiero mantener el estado de mis fragmentos sin tener que cargar todo desde 0 o estar agregando más información a la pila de la aplicación. Entonces, ¿que más puedo hacer?</p><h3>hide() &amp; show()</h3><p><em>E</em>l <strong><em>FragmentTransaction </em></strong>que nos permite acceder al método <em>replace</em> que maneja el cambio de nuestros fragmentos, maneja también una serie de operaciones como attach, detach, show, hide, add, isEmpty, etc; pero nos enfocaremos en los métodos <strong><em>hide</em></strong> and <strong><em>show.</em></strong></p><h4>Hide</h4><blockquote>Oculta un fragmento existente. Esto sólo es relevante para los fragmentos cuyas vistas han sido añadidas a un contenedor, ya que esto hará que se oculte la vista.(<a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction#hide">Android Developers</a>)</blockquote><h4>Show</h4><blockquote>Muestra un fragmento que esté oculto. Esto sólo es relevante para los fragmentos cuyas vistas han sido añadidas a un contenedor, ya que esto hará que se muestre la vista. (<a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction#show">Android Developers</a>)</blockquote><p>Entonces ahora, en lugar de destruir el fragmento y volverlo a recrear con un <strong><em>replace()</em></strong>, simplemente lo ocultaremos con un <strong><em>hide()</em></strong> y/o mostraremos con un <strong><em>show()</em></strong>. Ahora nuestro código se vería de la siguiente forma:</p><pre><strong>val </strong>transaction = <em>supportFragmentManager</em>.beginTransaction()<br><br><strong>if </strong>(fragment.<em>isAdded</em>) {<br>    transaction<br>            .hide(<strong>currentFragment</strong>)<br>            .show(fragment)<br>} <strong>else </strong>{<br>    transaction<br>            .hide(<strong>currentFragment</strong>)<br>            .add(R.id.<em>container</em>, fragment, tag)<br>}<br><br>transaction.commit()</pre><p>Como podemos ver, el mismo <strong><em>transaction</em></strong> que usábamos antes para usar el <strong><em>replace()</em></strong>, ahora oculta el fragmento actual (<strong><em>currentFragment</em></strong>) y muestra el que queramos mostrar (de nuevo valga la redundancia 😆) sin necesidad de usar el <strong><em>replace(), </em></strong>obviamente tenemos que asegurarnos que el fragmento a mostrar ya este agregado, ello lo hacemos con la propiedad <strong><em>isAdded, </em></strong>caso contrario lo agregamos con un<strong><em> add();</em></strong></p><p>Una diferencia respecto a nuestra anterior implementación es que usamos un <strong><em>tag</em></strong> cada vez que agregamos un nuevo fragmento, y esto es en caso necesitemos recuperar un fragmento específico en un momento dado, lo podemos encontrar por su <strong><em>tag</em></strong>. Sin embargo observamos que ya no usamos el método <strong><em>addToBackStack(tag), </em></strong>entonces ¿Cómo recuperamos nuestro anterior fragmento si deseo navegar entre ellos?.</p><pre><strong>override fun </strong>onBackPressed() {<br>   .<br>   .<br>        recoverFragment()<br>   .<br>   .</pre><pre>}</pre><p>Si el usuario usara el botón atrás para retroceder a su anterior fragmento o cree un botón que haga eso, podemos mover esa lógica a una función que me permita devolver el anterior fragmento en el cual estuve, y ¿Cómo lo recuperaría?.</p><pre><strong>val </strong>transaction = <em>supportFragmentManager</em>.beginTransaction()<br><br><strong>val </strong>currentFragment = <em>supportFragmentManager</em>.findFragmentByTag(<strong>currentFragmentTag</strong>)<br><strong>val </strong>oldFragment = <em>supportFragmentManager</em>.findFragmentByTag(<strong>oldFragmentTag</strong>)<br><br><strong>if </strong>(currentFragment.<em>isVisible </em>&amp;&amp; oldFragment.<em>isHidden</em>) {<br>    transaction.hide(currentFragment).show(oldFragment)<br>}<br><br>transaction.commit()</pre><p>Como pueden ver en el anterior código, primero recupero los fragmentos a mostrar/ocultar con ayuda del método <strong><em>findFragmentByTag(),</em></strong>en base a los <strong><em>tags</em></strong> que ya les asigné anteriormente. Lo siguiente a trabajar es ocultar o mostrar los fragmentos hallados, siempre verificando si están visibles o no con ayuda de los métodos “<strong><em>isVisible </em></strong>y<strong><em> isHidden”; </em></strong>todo esto debido a que el usuario quiera mostrar una vista que ya se esté mostrando o al revés, quiera ocultar una vista que ya esté oculta, a fin de evitar transacciones y errores innecesarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*ltj8IW9WiIi8t3S3llzeTg.gif" /></figure><h3>BONUS</h3><h4>Navegación en un Bottom Navigation</h4><p>Hablando de Bottom Navigation como menú en las aplicaciones, ¿Han visto el comportamiento de la barra de navegación de YouTube o Spotify?. Ambas son dos caras de la moneda, mientras el comportamiento de YouTube va de un histórico máximo de 5 tabs y luego home y exit; Spotify retrocede infinitamente todo el histórico que hallas hecho. Ambas tiene su pro y su contra, sin embargo comparten algo común, es que ambas respetan el estado de cada fragmento, es decir, si en una pantalla X hiciste scroll hasta la mitad de una lista o dejaste ciertos controles activados, etc; cuando regreses a ese fragmento, estará tal cual lo has dejado. ¿Como podríamos replicar este comportamiento?</p><pre><strong>when </strong>(<strong>listState</strong>.<strong>size</strong>) {<br>    <em>MAX_HISTORIC </em>-&gt; {<br><br>        <strong>...</strong><br><br>        <strong>for </strong>(i <strong>in listState</strong>.<em>indices</em>) {<br>            <strong>if </strong>(<strong>listState</strong>.<em>indices</em>.contains((i + 1))) {<br>                <strong>listState</strong>[i] = <strong>listState</strong>[i + 1]<br>            }<br>        }<br>      ...<br>    }<br>    <strong>else </strong>-&gt; {<br>        <strong>listState</strong>.add(StateFragment(<strong>currentFragmentTag</strong>, <strong>oldFragmentTag</strong>))<br>    }<br>}</pre><p>Creamos una lista donde agregas los estados de cada fragmento que quieras conservar, recuperar. Y luego en base a una lógica que definas, vas recuperando de tu lista los fragmentos que necesites, simulando tu propio Back Stack. En mi caso uso una variable <em>MAX_HISTORIC </em>donde defino el máximo histórico que deseo conservar. Sumado esto a la lógica que hemos armado en el presente post, tendremos un cambio entre nuestros fragmentos sin perder sus estados.</p><p>El código completo de este proyecto esta en el siguiente repositorio:</p><p><a href="https://github.com/Tohure/RecoverFragmentsWithoutLoseState">Tohure/RecoverFragmentsWithoutLoseState</a></p><h3>Referencias</h3><ul><li><a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack">Tasks and the back stack | App architecture | Android Developers</a></li><li><a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction#addtobackstack">FragmentTransaction | Android Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=febc7c2b16a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/orbismobile/navegando-entre-fragmentos-sin-perder-su-estado-android-febc7c2b16a7">Navegando entre fragmentos sin perder su estado | Android</a> was originally published in <a href="https://medium.com/orbismobile">OrbisMobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>