<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abanico SA on Medium]]></title>
        <description><![CDATA[Stories by Abanico SA on Medium]]></description>
        <link>https://medium.com/@abanico_sa?source=rss-912ddca67b67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*flnTUyGD8u8jAPZg.jpg</url>
            <title>Stories by Abanico SA on Medium</title>
            <link>https://medium.com/@abanico_sa?source=rss-912ddca67b67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:39:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abanico_sa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Arquitectura CLEAN con MVP, Dagger2, Retrofit2, Butterknife y RxJava]]></title>
            <link>https://medium.com/@abanico_sa/arquitectura-clean-con-mvp-dagger2-retrofit2-butterknife-y-rxjava-709db2fbf9fe?source=rss-912ddca67b67------2</link>
            <guid isPermaLink="false">https://medium.com/p/709db2fbf9fe</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[mvp]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Abanico SA]]></dc:creator>
            <pubDate>Tue, 17 Mar 2020 07:21:37 GMT</pubDate>
            <atom:updated>2020-03-17T07:21:37.809Z</atom:updated>
            <content:encoded><![CDATA[<p>El mercado de apps para Android crece constantemente sin parar con miles de nuevas aplicaciones nuevas lanzadas cada día. Esta competición por sacar más y más apps, se convierte en un dolor de cabeza para los desarrolladores, que ahora deben añadir nuevas aplicaciones para mantenerse en la ola pero también actualizar las antiguas con nuevas funcionalidades, nuevo contenido que mantenga al usuario activo en las mismas. Esto significa que los desarrolladores de aplicaciones móviles tenemos que escribir código que sea capaz de balancear la creación de código y la optimización del código de nuestros productos. Al mismo tiempo, tenemos que considerar los estándares de programación, la usabilidad del producto y su escalabilidad cuando creamos una app. Porque además de ser productos para el usuario, las apps necesitan de un nivel de tecnología y programación muy elevado y por tanto tiene que respetar las normas de la comunidad técnica. Sobretodo si estamos trabajando en un equipo de desarrolladores donde todos tenemos que hablar el mismo lenguaje para comunicarnos cuando leemos y usamos el código de otro.</p><h3>Los patrones de diseño</h3><p>Un patrón de diseño no es más que una solución probada y testeada para resolver el problema en su forma lo más general posible. En particular, los patrones de arquitectura o arquetipos dan una descripción de los elementos y el tipo de relación que tienen junto con un conjunto de restricciones sobre cómo pueden ser usados. Los desarrolladores los usamos para ahorrar tiempo en la fase de desarrollo porque sabemos que funcionan y han sido ampliamente probados.</p><h3>MVP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*nV6o2rmO8djyi6oq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*asM4oyGxwxvNrBN-.png" /></figure><p>MVP es un patrón arquitectónico de interfaz de usuario diseñada para facilitar pruebas de unidad automatizada y mejorar la separación de inquietudes en lógica de presentación:</p><p>El modelo es una interface que define los datos que serán usados en la app y, en última instancia, cargados en la interfaz gráfica de usuario.</p><p>El presenter será el mediador entre el modelo de datos y la vista. Se encargará de recuperar datos desde repositorios o bases de datos (el modelo) y darle el formato necesario para que se muestren en la vista.</p><p>La vista finalmente es una interfaz pasiva que se encargará de mostrar los datos del modelo y localizar los comandos e interacción del usuario con la pantalla (los eventos) para notificarlos al presenter y que este pueda actuar en base a ellos.</p><p>MVP nos va a permitir solventar la mayoría de problemas y dificultades que nos encontramos en las apps de Android, especialmente los que se refieren a mantener y probar nuestro código. En el MVP podemos separar tareas en segundo plano de las actividades, las vistas o los fragmentos haciendo que sean totalmente independientes de la mayoría de eventos relacionados con los eventos del ciclo de vida de la app. De este modo, una app será más simple, más robusta, el código mucho más limpio, más fácil de mantener y sobretodo, desde mi punto de vista, hacer apps se convierte en algo ameno y divertido.</p><p>Uno de los objetivos fundamentales del patrón mvp es hacer nuestro código más fácil de leer y más limpio. El código más simple suele ser el mejor, pero ¿cómo podemos simplificarlo? Según la representación más clásica de la arquitectura clean, las capas tienen que ser modificables y testeadas independientemente del framework, la base de datos, la UI u otra dependencia externa. Las entidades encapsulan reglas de negocio de forma amplia. Una entidad puede ser un objeto con métodos o incluso estructuras de datos y funciones. En general no importa mientras estas puedan ser usadas por diferentes aplicaciones de la empresa, de ahí que se llame lógica de negocio. Por ejemplo, los mismos objetos pueden usarse en una aplicación, en un dashboard, en un webservice, en una página web… Encapsulan las reglas de alto nivel más genéricas. Es la capa que es menos probable que sufra modificaciones a lo largo del tiempo, por ejemplo debido a un cambio en la página web o cuestiones de seguridad. Ninguna modificación operacional debería afectar a ningún elemento de la capa de entidades.</p><p>En resumen, el mvp intenta mantener las cosas simples, implementar nuestro código en capas en lugar de en ficheros de código eternos, evitar dependencias directas del framework de Android y tener en cuenta la regla de dependencia. Si tenemos en cuenta estos aspectos, nos ahorraremos muchos dolores de cabeza en el futuro. Crearemos un sistema fácil de testear con muchos beneficios y fácil de mantener. Cuando cualquier parte externa del sistema se vuelva obsoleta, por ejemplo la base de datos, el framework de web… lo podremos reemplazar con esfuerzo mínimo y sin afectar al resto de capas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*MDc0FF3_nAuUUMU3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*7YwArLSAoTAvarVt" /></figure><p>En este articulo, además de usar el patrón arquitectónico MVP basado en la Arquitectura Clean, vamos a usar otras librerías de gran ayuda para nuestro desarrollo, las siguiente son RxJava, Dagger2, Retrofit 2 y Butterknife.</p><h3>RxJava:</h3><p>RxJava es una librería que trata de facilitar la programación asíncrona y basada en eventos mediante el uso de <strong>Observables</strong>. Se basa en el patrón <em>Observer</em> al que le añade operadores que nos permiten componer distintos <strong>Observable</strong> además de ayudarnos a abstraernos de problemas cómo <em>threading</em> y <em>sincronización</em>.</p><h3>Retrofit 2:</h3><p><em>Retrofit es un cliente REST para Android y Java, desarrollada por Square, muy simple y fácil de aprender. Permite hacer peticiones GET, POST, PUT, PATCH, DELETE y HEAD , gestionar diferentes tipos de parámetros y parsear automáticamente la respuesta a un POJO.</em></p><h3>Dagger 2:</h3><p>Dagger es una librería, actualmente de Google, para inyección de dependencia (DI). La DI es una solución que tienen los desarrolladores para modularizar la creación de objetos y encapsular sus instancias. A pesar de que la DI tiene una integración compleja, su implementación es prácticamente obligatoria en cualquier proyecto actual, ya que su potencial y posibilidad de personalización para la creación de instancias con Dagger son muy potentes.</p><h3>Butterknife:</h3><p><a href="https://github.com/JakeWharton/butterknife">Butterknife</a> es una librería que nos facilitará la tarea de relacionar los elementos de las vistas con el código en nuestras aplicaciones Android. Nos evitará tener que utilizar findViewById y simplificará el código en otros aspectos.</p><h3>¡Manos a la obra!</h3><p>Vamos a crear un proyecto nuevo, y lo primeros que haremos es agregar dependencias para todas las bibliotecas necesarias. Agregue las siguientes bibliotecas a su build.gradle (Módulo: aplicación), es decir, a nivel de aplicación.</p><pre>//dagger<br>implementation &#39;com.google.dagger:dagger:2.15&#39;<br>implementation &#39;com.google.dagger:dagger-android-support:2.15&#39;<br>implementation &#39;com.google.dagger:dagger-android:2.15&#39;<br>implementation &#39;androidx.legacy:legacy-support-v4:1.0.0&#39;<br>annotationProcessor &#39;com.google.dagger:dagger-android-processor:2.15&#39;<br>annotationProcessor &#39;com.google.dagger:dagger-compiler:2.15&#39;<br>//RxJava<br>implementation &#39;io.reactivex.rxjava2:rxandroid:2.1.0&#39;<br>implementation &#39;io.reactivex.rxjava2:rxjava:2.2.0&#39;<br>//retrofit<br>implementation &#39;com.squareup.retrofit2:adapter-rxjava2:2.5.0&#39;<br>implementation &#39;com.squareup.retrofit2:converter-gson:2.4.0&#39;<br>implementation &#39;com.squareup.retrofit2:retrofit:2.5.0&#39;<br>implementation &#39;com.squareup.retrofit2:converter-scalars:2.3.0&#39;<br>//ButterKnife<br>implementation &#39;com.jakewharton:butterknife:10.2.0&#39;<br>annotationProcessor &#39;com.jakewharton:butterknife-compiler:10.2.0&#39;<br>//gson<br>implementation &#39;com.google.code.gson:gson:2.8.5&#39;<br>//okhttp<br>implementation &#39;com.squareup.okhttp3:okhttp:3.12.0&#39;<br>implementation &#39;com.squareup.okhttp3:logging-interceptor:3.11.0&#39;</pre><p>Además, también vamos a configurar nuestro archivo build.gradle para que nos permita usar las funciones del lenguaje Java 8, vamos a agregar el compileOptions de la siguiente manera por debajo de nuestro defaultConfig:</p><pre>android {<br>    compileSdkVersion 29<br>    buildToolsVersion &quot;29.0.2&quot;<br>    defaultConfig {<br>        applicationId &quot;com.abanicosa.examplemedium&quot;<br>        minSdkVersion 21<br>        targetSdkVersion 29<br>        versionCode 1<br>        versionName &quot;1.0&quot;<br>        testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;<br>    }<br>    compileOptions {<br>        sourceCompatibility JavaVersion.VERSION_1_8<br>        targetCompatibility JavaVersion.VERSION_1_8<br>    }<br>    buildTypes {<br>        release {<br>            minifyEnabled false<br>            proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;<br>        }<br>    }<br>}</pre><p>Ahora crearemos nuestra interfaz visual, simple y sencilla, para ingresar usuario y clave para el login en la app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*oNdBJWywVRFI-m9l" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/0*ULRvamK0RkdNGWEG.png" /></figure><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/cl_principal_login&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot; &gt;</pre><pre>    &lt;ProgressBar<br>        android:id=&quot;@+id/pb_loading_login&quot;<br>        style=&quot;?android:attr/progressBarStyleHorizontal&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;5dp&quot;<br>        android:indeterminate=&quot;true&quot;<br>        android:scaleY=&quot;1.5&quot;<br>        android:visibility=&quot;invisible&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;</pre><pre>    &lt;EditText<br>        android:id=&quot;@+id/et_user_login&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;16dp&quot;<br>        android:layout_marginTop=&quot;150dp&quot;<br>        android:layout_marginEnd=&quot;16dp&quot;<br>        android:ems=&quot;10&quot;<br>        android:hint=&quot;Usuario&quot;<br>        android:inputType=&quot;textPersonName&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;</pre><pre>    &lt;EditText<br>        android:id=&quot;@+id/et_password_login&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;16dp&quot;<br>        android:layout_marginTop=&quot;32dp&quot;<br>        android:layout_marginEnd=&quot;16dp&quot;<br>        android:ems=&quot;10&quot;<br>        android:hint=&quot;Clave&quot;<br>        android:inputType=&quot;textPassword&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/et_user_login&quot; /&gt;</pre><pre>    &lt;Button<br>        android:id=&quot;@+id/btn_login&quot;<br>        android:layout_width=&quot;0dp&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginStart=&quot;32dp&quot;<br>        android:layout_marginEnd=&quot;32dp&quot;<br>        android:background=&quot;@android:color/black&quot;<br>        android:text=&quot;Ingresar&quot;<br>        android:textAllCaps=&quot;false&quot;<br>        android:textColor=&quot;@android:color/white&quot;<br>        android:textSize=&quot;20sp&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/et_password_login&quot; /&gt;</pre><pre>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>Ahora, cree la interfaz PrincipalApi para la configuración de Retrofit. Define las llamadas a la API que se realizarán.</p><pre>import com.abanicosa.examplemedium.data.api.pojo.LoginResponse;<br>import io.reactivex.Observable;<br>import retrofit2.http.Field;<br>import retrofit2.http.FormUrlEncoded;<br>import retrofit2.http.Headers;<br>import retrofit2.http.POST;</pre><pre>public interface PrincipalApi {</pre><pre>    @Headers({&quot;Content-Type: application/x-www-form-urlencoded&quot;, &quot;Accept: application/json&quot;})<br>    @FormUrlEncoded<br>    @POST(&quot;oauth/token&quot;)<br>    Observable&lt;LoginResponse&gt; postLogin(@Field(&quot;client_id&quot;) String clientId, @Field(&quot;client_secret&quot;) String clientSecret,<br>                                        @Field(&quot;username&quot;) String username, @Field(&quot;password&quot;) String password, @Field(&quot;grant_type&quot;) String grantType);</pre><pre>}</pre><p>Ahora cree una clase de datos POJO como modelo que analizaría la respuesta de la llamada API. Dependiendo de la llamada, este es un ejemplo de cómo puede ser una respuesta. Está sujeto a diferentes cambios y formas. Puede editar fácilmente el modelo para que se ajuste a su respuesta.</p><pre>import com.google.gson.annotations.Expose;<br>import com.google.gson.annotations.SerializedName;</pre><pre>public class LoginResponse {</pre><pre>    @SerializedName(&quot;token_type&quot;)<br>    @Expose<br>    private String tokenType;<br>    @SerializedName(&quot;expires_in&quot;)<br>    @Expose<br>    private String expiresIn;<br>    @SerializedName(&quot;access_token&quot;)<br>    @Expose<br>    private String accessToken;<br>    @SerializedName(&quot;refresh_token&quot;)<br>    @Expose<br>    private String refreshToken;<br>    @SerializedName(&quot;perfil&quot;)<br>    @Expose<br>    private Perfil perfil;</pre><pre>    <em>/**<br>     * No args constructor for use in serialization<br>     */<br>    </em>public LoginResponse() {}</pre><pre>    <em>/**<br>     * </em><strong><em>@param </em></strong><em>expiresIn<br>     * </em><strong><em>@param </em></strong><em>tokenType<br>     * </em><strong><em>@param </em></strong><em>accessToken<br>     * </em><strong><em>@param </em></strong><em>refreshToken<br>     * </em><strong><em>@param </em></strong><em>perfil<br>     */<br>    </em>public LoginResponse(String tokenType, String expiresIn, String accessToken, String refreshToken, Perfil perfil) {<br>        super();<br>        this.tokenType = tokenType;<br>        this.expiresIn = expiresIn;<br>        this.accessToken = accessToken;<br>        this.refreshToken = refreshToken;<br>        this.perfil = perfil;<br>    }</pre><pre>    public String getTokenType() {<br>        return tokenType;<br>    }</pre><pre>    public void setTokenType(String tokenType) {<br>        this.tokenType = tokenType;<br>    }</pre><pre>    public String getExpiresIn() {<br>        return expiresIn;<br>    }</pre><pre>    public void setExpiresIn(String expiresIn) {<br>        this.expiresIn = expiresIn;<br>    }</pre><pre>    public String getAccessToken() {<br>        return accessToken;<br>    }</pre><pre>    public void setAccessToken(String accessToken) {<br>        this.accessToken = accessToken;<br>    }</pre><pre>    public String getRefreshToken() {<br>        return refreshToken;<br>    }</pre><pre>    public void setRefreshToken(String refreshToken) {<br>        this.refreshToken = refreshToken;<br>    }</pre><pre>    public Perfil getPerfil() {<br>        return perfil;<br>    }</pre><pre>    public void setPerfil(Perfil perfil) {<br>        this.perfil = perfil;<br>    }<br>}</pre><p>Y el otro POJO que necesitamos es el Perfil:</p><pre>import com.google.gson.annotations.Expose;<br>import com.google.gson.annotations.SerializedName;</pre><pre>public class Perfil {</pre><pre>    @SerializedName(&quot;nombre&quot;)<br>    @Expose<br>    private String nombre;<br>    @SerializedName(&quot;apellido&quot;)<br>    @Expose<br>    private String apellido;<br>    @SerializedName(&quot;email&quot;)<br>    @Expose<br>    private String email;<br>    @SerializedName(&quot;celular&quot;)<br>    @Expose<br>    private String celular;</pre><pre>    <em>/**<br>     * No args constructor for use in serialization<br>     *<br>     */<br>    </em>public Perfil() {<br>    }</pre><pre>    <em>/**<br>     *<br>     * </em><strong><em>@param </em></strong><em>apellido<br>     * </em><strong><em>@param </em></strong><em>celular<br>     * </em><strong><em>@param </em></strong><em>nombre<br>     * </em><strong><em>@param </em></strong><em>email<br>     */<br>    </em>public Perfil(String nombre, String apellido, String email, String celular) {<br>        super();<br>        this.nombre = nombre;<br>        this.apellido = apellido;<br>        this.email = email;<br>        this.celular = celular;<br>    }</pre><pre>    public String getNombre() {<br>        return nombre;<br>    }</pre><pre>    public void setNombre(String nombre) {<br>        this.nombre = nombre;<br>    }</pre><pre>    public String getApellido() {<br>        return apellido;<br>    }</pre><pre>    public void setApellido(String apellido) {<br>        this.apellido = apellido;<br>    }</pre><pre>    public String getEmail() {<br>        return email;<br>    }</pre><pre>    public void setEmail(String email) {<br>        this.email = email;<br>    }</pre><pre>    public String getCelular() {<br>        return celular;<br>    }</pre><pre>    public void setCelular(String celular) {<br>        this.celular = celular;<br>    }<br>}</pre><p>Guardaremos el token del usuario y alguno de sus datos en un SharedPreferences, así con esto podremos mostrar esta información en otra activity. Esta es la clase.</p><pre>import android.content.SharedPreferences;<br>import javax.inject.Inject;<br>import javax.inject.Singleton;</pre><pre>@Singleton<br>public class PrincipalSP {</pre><pre>    private SharedPreferences prefs;<br>    private SharedPreferences.Editor editor;</pre><pre>    <em>/**TOKEN DE USUARIO LOGUEADO**/<br>    </em>private String SHAREDPREFERENCE_TOKEN = &quot;token&quot;;<br>    private String SHAREDPREFERENCE_REFRESH_TOKEN = &quot;refreshToken&quot;;</pre><pre>    <em>/**DATOS REGISTRO USUARIO Y PARA CUANDO USUARIO YA ESTA LOGUEADO**/<br>    </em>private String SHAREDPREFERENCE_NOMBRE = &quot;nombre&quot;;<br>    private String SHAREDPREFERENCE_APELLIDO = &quot;apellido&quot;;<br>    private String SHAREDPREFERENCE_TELEFONO = &quot;telefono&quot;;<br>    private String SHAREDPREFERENCE_EMAIL = &quot;email&quot;;</pre><pre>    @Inject<br>    public PrincipalSP(SharedPreferences mSharedPreferences) {<br>        this.prefs = mSharedPreferences;<br>        editor = prefs.edit();<br>    }</pre><pre>    public void setToken(String token){<br>        editor.putString(SHAREDPREFERENCE_TOKEN,token);<br>        editor.commit();<br>    }<br>    public String getToken(){<br>        return prefs.getString(SHAREDPREFERENCE_TOKEN,&quot;&quot;);<br>    }</pre><pre>    public void setRefreshToken(String refreshToken){<br>        editor.putString(SHAREDPREFERENCE_REFRESH_TOKEN,refreshToken);<br>        editor.commit();<br>    }<br>    public String getRefreshToken(){<br>        return prefs.getString(SHAREDPREFERENCE_REFRESH_TOKEN,&quot;&quot;);<br>    }</pre><pre>    public void setNombre(String value){<br>        editor.putString(SHAREDPREFERENCE_NOMBRE,value);<br>        editor.commit();<br>    }<br>    public String getNombre(){<br>        return prefs.getString(SHAREDPREFERENCE_NOMBRE,&quot;&quot;);<br>    }</pre><pre>    public void setApellido(String value){<br>        editor.putString(SHAREDPREFERENCE_APELLIDO,value);<br>        editor.commit();<br>    }<br>    public String getApellido(){<br>        return prefs.getString(SHAREDPREFERENCE_APELLIDO,&quot;&quot;);<br>    }</pre><pre>    public void setTelefono(String value){<br>        editor.putString(SHAREDPREFERENCE_TELEFONO,value);<br>        editor.commit();<br>    }<br>    public String getTelefono(){<br>        return prefs.getString(SHAREDPREFERENCE_TELEFONO,&quot;&quot;);<br>    }</pre><pre>    public void setEmail(String value){<br>        editor.putString(SHAREDPREFERENCE_EMAIL,value);<br>        editor.commit();<br>    }<br>    public String getEmail(){<br>        return prefs.getString(SHAREDPREFERENCE_EMAIL,&quot;&quot;);<br>    }<br></pre><pre>    public void limpiarSP(){<br>        editor.clear();<br>        editor.commit();<br>    }<br>}</pre><p>Preste atención a la anotación “@Singleton”, está nos servirá para conseguir una única instancia de esta clase para cuando creemos el modulo de la aplicación con Dagger2</p><p>Bien, ahora vamos a crear clases Base para nuestras vistas y presenters, así ahorramos varias lineas de código y logramos que nuestro proyecta tenga una mejor forma para ser aún mas entendible. Empezamos con la interfaz que implementará el BaseActivity.</p><pre>public interface MvpView {</pre><pre>    void loading();<br>    void finishLoading();<br>    void showError(int idMessage);</pre><pre>}</pre><p>Ahora con la interfaz base del presenter.</p><pre>public interface MvpPresenter&lt;V extends MvpView&gt; {</pre><pre>    void setView(V view);<br>    V getView();<br>    void handleApiError(Throwable error);<br>}</pre><p>Implementamos esta interfaz en una clase abstracta para hacerla así nuestra BaseActivity.</p><pre>import android.app.Activity;<br>import android.os.Bundle;<br>import android.os.PersistableBundle;<br>import android.view.MotionEvent;<br>import android.view.inputmethod.InputMethodManager;<br>import androidx.annotation.Nullable;<br>import androidx.appcompat.app.AppCompatActivity;<br>import com.abanicosa.examplemedium.utils.CustomToast;</pre><pre>public abstract class BaseActivity extends AppCompatActivity implements MvpView {</pre><pre>    @Override<br>    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {<br>        super.onCreate(savedInstanceState, persistentState);<br>    }</pre><pre>    @Override<br>    public void loading(){}</pre><pre>    @Override<br>    public void finishLoading(){}</pre><pre>    @Override<br>    public void showError(int idMessage) {<br>        CustomToast.<em>verToastLargo</em>(getApplicationContext(),getString(idMessage));<br>    }</pre><pre>    @Override<br>    public boolean dispatchTouchEvent(MotionEvent ev) {<br>        if (getCurrentFocus() != null){<br>            try{<br>                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.<em>INPUT_METHOD_SERVICE</em>);<br>                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);<br>            }catch (Exception e){e.printStackTrace();}<br>        }<br>        return super.dispatchTouchEvent(ev);<br>    }<br>}</pre><p>y en el presenter.</p><pre>import com.abanicosa.examplemedium.R;<br>import com.google.gson.JsonSyntaxException;<br>import retrofit2.HttpException;</pre><pre>public class BasePresenter&lt;V extends MvpView&gt; implements MvpPresenter&lt;V&gt; {</pre><pre>    private V view;</pre><pre>    @Override<br>    public void setView(V view) {<br>        this.view = view;<br>    }</pre><pre>    @Override<br>    public V getView() {<br>        return view;<br>    }</pre><pre>    @Override<br>    public void handleApiError(Throwable error) {<br>        view.finishLoading();<br>        if (error instanceof HttpException) {<br>            switch (((HttpException) error).code()) {<br>                case 400:<br>                    view.showError(R.string.<em>error_datos_mal_ingresados</em>);<br>                    break;<br>                case 401:<br>                case 403:<br>                    view.showError(R.string.<em>error_no_autorizado</em>);<br>                    break;<br>                case 404:<br>                    view.showError(R.string.<em>error_dato_no_encontrado</em>);<br>                    break;<br>                default:<br>                    view.showError(R.string.<em>error_servidor</em>);<br>                    break;<br>            }<br>        }<br>        else if (error instanceof JsonSyntaxException) view.showError(R.string.<em>error_sintaxis_json</em>);<br>        else view.showError(R.string.<em>no_hay_conexion</em>);<br>    }<br>}</pre><p>Con esto ya podemos heredar cualquier activity o presenter de su base correspondiente y así sobrescribir los métodos que sean necesarios en cada caso.</p><p>Ahora creamos el componente de la aplicación para Dagger2. Este realizará la inyección de dependencia real de nuestras vistas y, además, de nuestro sahredPreferences para este ejemplo.</p><pre>import com.abanicosa.examplemedium.data.pref.PrincipalSP;<br>import com.abanicosa.examplemedium.di.LoginModule;<br>import com.abanicosa.examplemedium.di.MainMenuModule;<br>import com.abanicosa.examplemedium.di.PrincipalApiModule;<br>import com.abanicosa.examplemedium.ui.login.LoginActivity;<br>import com.abanicosa.examplemedium.ui.menu.MainMenuActivity;<br>import javax.inject.Singleton;<br>import dagger.Component;</pre><pre>@Singleton<br>@Component(modules = {<br>        ApplicationModule.class,<br>        LoginModule.class,<br>        MainMenuModule.class,<br>        PrincipalApiModule.class<br>})<br>public interface ApplicationComponent {<br>    PrincipalSP getSharedPrefs();<br>    void injectLogin(LoginActivity target);<br>    void injectMainMenu(MainMenuActivity target);<br>}</pre><p>observemos que estamos necesitando de los módulos para que esto funcione, ahora crearemos los mismos.</p><p>Empezamos con el ApplicationModule.</p><pre>import android.app.Application;<br>import android.content.Context;<br>import com.abanicosa.examplemedium.data.pref.PrincipalSP;<br>import javax.inject.Singleton;<br>import dagger.Module;<br>import dagger.Provides;</pre><pre>@Module<br>public class ApplicationModule {</pre><pre>    private Application application;</pre><pre>    public ApplicationModule(Application app){<br>        this.application = app;<br>    }</pre><pre>    @Provides<br>    @Singleton<br>    public Context provideContext(){<br>        return application;<br>    }</pre><pre>    @Provides<br>    @Singleton<br>    PrincipalSP provideSharedPrefs() {<br>        return new PrincipalSP(application.getSharedPreferences(&quot;PRINCIPAL_SP&quot;,Context.<em>MODE_PRIVATE</em>));<br>    }<br>}</pre><p>LoginModule</p><pre>import com.abanicosa.examplemedium.data.api.PrincipalApi;<br>import com.abanicosa.examplemedium.data.entity.RepositoryUser;<br>import com.abanicosa.examplemedium.data.entity.UserRepository;<br>import com.abanicosa.examplemedium.data.pref.PrincipalSP;<br>import com.abanicosa.examplemedium.ui.login.LoginContract;<br>import com.abanicosa.examplemedium.ui.login.LoginModel;<br>import com.abanicosa.examplemedium.ui.login.LoginPresenter;<br>import javax.inject.Singleton;<br>import dagger.Module;<br>import dagger.Provides;</pre><pre>@Module<br>public class LoginModule {</pre><pre>    @Provides<br>    public LoginContract.Presenter providePresenter(LoginContract.Model model){<br>        return new LoginPresenter(model);<br>    }</pre><pre>    @Provides<br>    public LoginContract.Model provideModel(RepositoryUser repository){<br>        return new LoginModel(repository);<br>    }</pre><pre>    @Singleton<br>    @Provides<br>    public RepositoryUser provideLoginRepository(PrincipalApi api, PrincipalSP pref){<br>        return new UserRepository(api,pref);<br>    }<br>}</pre><p>MainModule</p><pre>import com.abanicosa.examplemedium.data.entity.RepositoryUser;<br>import com.abanicosa.examplemedium.ui.menu.MainMenuContract;<br>import com.abanicosa.examplemedium.ui.menu.MainMenuModel;<br>import com.abanicosa.examplemedium.ui.menu.MainMenuPresenter;<br>import dagger.Module;<br>import dagger.Provides;</pre><pre>@Module<br>public class MainMenuModule {</pre><pre>    @Provides<br>    public MainMenuContract.Presenter providePresenter(MainMenuContract.Model model){<br>        return new MainMenuPresenter(model);<br>    }</pre><pre>    @Provides<br>    public MainMenuContract.Model provideModel(RepositoryUser repository){<br>        return new MainMenuModel(repository);<br>    }<br>}</pre><p>PrincipalApi</p><pre>import com.abanicosa.examplemedium.data.api.PrincipalApi;<br>import dagger.Module;<br>import dagger.Provides;<br>import okhttp3.OkHttpClient;<br>import okhttp3.logging.HttpLoggingInterceptor;<br>import retrofit2.Retrofit;<br>import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;<br>import retrofit2.converter.gson.GsonConverterFactory;</pre><pre>@Module<br>public class PrincipalApiModule {</pre><pre>    public final String BASE_URL = &quot;https://your base url .com/&quot;;</pre><pre>    @Provides<br>    public OkHttpClient provideClient(){</pre><pre>        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();<br>        interceptor.setLevel(HttpLoggingInterceptor.Level.<em>BODY</em>);<br>        return new OkHttpClient.Builder().addInterceptor(interceptor).build();<br>    }</pre><pre>    @Provides<br>    public Retrofit provideRetrofit(String baseUrl, OkHttpClient client){<br>        return new Retrofit.Builder()<br>                .baseUrl(baseUrl)<br>                .client(client)<br>                .addCallAdapterFactory(RxJava2CallAdapterFactory.<em>create</em>())<br>                .addConverterFactory(GsonConverterFactory.<em>create</em>())<br>                .build();<br>    }</pre><pre>    @Provides<br>    public PrincipalApi providePrincipalApi(){<br>        return provideRetrofit(BASE_URL, provideClient()).create(PrincipalApi.class);<br>    }<br>}</pre><p>Ahora mismo está teniendo errores por falta de clases en LoginModule y MainModule, eso es por lo que aún no creamos su MVP, es con lo que seguiremos ahora.</p><p>Observemos el LoginContract.</p><pre>import com.abanicosa.examplemedium.ui.base.MvpPresenter;<br>import com.abanicosa.examplemedium.ui.base.MvpView;<br>import io.reactivex.Observable;</pre><pre>public interface LoginContract {</pre><pre>    interface View extends MvpView {<br>        void loggedUser();<br>    }</pre><pre>    interface Presenter&lt;V extends LoginContract.View&gt; extends MvpPresenter&lt;V&gt; {<br>        void loginUser(String username, String password);<br>        void verifyUserLogged();<br>    }</pre><pre>    interface Model {<br>        Observable&lt;Integer&gt; loginUser(String username, String password);<br>        boolean isUserLogged();<br>    }<br>}</pre><p>se observa claramente el patrón MVP, una vez que el usuario carga sus datos y presiona en el botón “ingresar”</p><pre>import android.content.Intent;<br>import android.os.Bundle;<br>import android.view.View;<br>import android.widget.EditText;<br>import android.widget.ProgressBar;<br>import com.abanicosa.examplemedium.R;<br>import com.abanicosa.examplemedium.di.root.App;<br>import com.abanicosa.examplemedium.ui.base.BaseActivity;<br>import com.abanicosa.examplemedium.ui.menu.MainMenuActivity;<br>import javax.inject.Inject;<br>import butterknife.BindView;<br>import butterknife.ButterKnife;<br>import butterknife.OnClick;</pre><pre>public class LoginActivity extends BaseActivity implements LoginContract.View {</pre><pre>    @Inject<br>    LoginContract.Presenter presenter;</pre><pre>    @BindView(R.id.<em>et_user_login</em>)<br>    EditText etUsername;</pre><pre>    @BindView(R.id.<em>et_password_login</em>)<br>    EditText etPassowrd;</pre><pre>    @BindView(R.id.<em>pb_loading_login</em>)<br>    ProgressBar pbLoading;</pre><pre>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_login</em>);</pre><pre>        ButterKnife.<em>bind</em>(this);<br>        ((App) getApplication()).getComponent().injectLogin(this);</pre><pre>    }</pre><pre>    @OnClick(R.id.<em>btn_login</em>) public void loginUser(){<br>        presenter.loginUser(etUsername.getText().toString(),etPassowrd.getText().toString());<br>    }</pre><pre>    @Override<br>    protected void onResume() {<br>        super.onResume();<br>        presenter.setView(this);<br>        presenter.verifyUserLogged();<br>    }</pre><pre>    @Override<br>    public void loading() {<br>        pbLoading.setVisibility(View.<em>VISIBLE</em>);<br>    }</pre><pre>    @Override<br>    public void finishLoading() {<br>        pbLoading.setVisibility(View.<em>INVISIBLE</em>);<br>    }</pre><pre>    @Override<br>    public void loggedUser() {<br>        startActivity(new Intent(getApplicationContext(), MainMenuActivity.class));<br>    }<br>}</pre><p>El presenter comenzará con su función “loginUser”, aquí comenzamos con el uso de la programación Reactiva, que se basa en el patrón Observer (Observador y Subscriptor)</p><pre>import com.abanicosa.examplemedium.R;<br>import com.abanicosa.examplemedium.ui.base.BasePresenter;<br>import io.reactivex.android.schedulers.AndroidSchedulers;<br>import io.reactivex.disposables.Disposable;<br>import io.reactivex.observers.DisposableObserver;<br>import io.reactivex.schedulers.Schedulers;</pre><pre>public class LoginPresenter&lt;V extends LoginContract.View&gt; extends BasePresenter&lt;V&gt; implements LoginContract.Presenter&lt;V&gt;{</pre><pre>    private LoginContract.Model model;<br>    private Disposable subLogin = null;</pre><pre>    public LoginPresenter(LoginContract.Model model){<br>        this.model = model;<br>    }</pre><pre>    @Override<br>    public void loginUser(String username, String password) {<br>        getView().loading();<br>        subLogin = model.loginUser(username, password)<br>                .subscribeOn(Schedulers.<em>io</em>())<br>                .observeOn(AndroidSchedulers.<em>mainThread</em>())<br>                .subscribeWith(new DisposableObserver&lt;Integer&gt;() {<br>                    @Override<br>                    public void onNext(Integer message) {<br>                        getView().finishLoading();<br>                        if (message.equals(R.string.<em>ok</em>)) getView().loggedUser();<br>                        else getView().showError(message);<br>                    }</pre><pre>                    @Override<br>                    public void onError(Throwable e) {<br>                        handleApiError(e);<br>                    }</pre><pre>                    @Override<br>                    public void onComplete(){}<br>                });<br>    }</pre><pre>    @Override<br>    public void verifyUserLogged() {<br>        if (model.isUserLogged()) getView().loggedUser();<br>    }<br>}</pre><p>el presenter estará subscrito al Modelo (“LoginModel”) , específicamente a la función “loginUser”, ya que se encargará de crear el Observador del cual estará pendiente nuestro presentador</p><pre>import com.abanicosa.examplemedium.R;<br>import com.abanicosa.examplemedium.data.api.pojo.LoginResponse;<br>import com.abanicosa.examplemedium.data.entity.RepositoryUser;<br>import io.reactivex.Observable;<br>import io.reactivex.functions.Function;</pre><pre>public class LoginModel implements LoginContract.Model {</pre><pre>    private RepositoryUser repository;</pre><pre>    public LoginModel(RepositoryUser repository){<br>        this.repository = repository;<br>    }</pre><pre>    @Override<br>    public Observable&lt;Integer&gt; loginUser(String username, String password) {</pre><pre>        if (username.length() != 10) return Observable.<em>just</em>(R.string.<em>error_username</em>);<br>        else if (password.length() != 6) return Observable.<em>just</em>(R.string.<em>error_password</em>);<br>        else {<br>            return Observable.<em>wrap</em>(repository.loginUser(username,password).map(new Function&lt;LoginResponse, Integer&gt;() {<br>                @Override<br>                public Integer apply(LoginResponse response) throws Exception {<br>                    return R.string.<em>ok</em>;<br>                }<br>            }));<br>        }<br>    }</pre><pre>    @Override<br>    public boolean isUserLogged() {<br>        if (repository.isUserLogged()) return true;<br>        else return false;<br>    }<br>}</pre><p>Bien, desde el modelo, es que ya incluimos otro patrón de diseño muy importante, el Repository. Aquí lo usaremos para poder discriminar consultas (en este caso de usuarios) ya sea que vengan de una BD, o de una API, o de un sharedPreferences (nosotros usamos los dos ultimos casos).</p><p>RepositoryUser</p><pre>import com.abanicosa.examplemedium.data.api.pojo.LoginResponse;<br>import io.reactivex.Observable;</pre><pre>public interface RepositoryUser {</pre><pre>    Observable&lt;LoginResponse&gt; loginUser(String username, String password);<br>    User getUser();<br>    boolean logout();<br>    boolean isUserLogged();<br>}</pre><p>UserRepository</p><pre>import com.abanicosa.examplemedium.data.api.PrincipalApi;<br>import com.abanicosa.examplemedium.data.api.pojo.LoginResponse;<br>import com.abanicosa.examplemedium.data.pref.PrincipalSP;<br>import io.reactivex.Observable;<br>import io.reactivex.ObservableSource;<br>import io.reactivex.functions.Function;</pre><pre>public class UserRepository implements RepositoryUser {</pre><pre>    private PrincipalSP pref;<br>    private PrincipalApi api;</pre><pre>    public UserRepository(PrincipalApi api, PrincipalSP pref){<br>        this.pref = pref;<br>        this.api = api;<br>    }</pre><pre>    @Override<br>    public Observable&lt;LoginResponse&gt; loginUser(String username, String password) {<br>        String clientId = &quot;1&quot;;<br>        String clientSecret = &quot;LpqlaJ874yUYBMOMm7qA3yThaqkRnfl7DMKAGBA&quot;;<br>        String grantType = &quot;password&quot;;<br>            Observable&lt;LoginResponse&gt; user = api.postLogin(clientId,clientSecret, username, password,grantType);<br>            return user.concatMap(new Function&lt;LoginResponse, ObservableSource&lt;? extends LoginResponse&gt;&gt;() {<br>                @Override<br>                public ObservableSource&lt;? extends LoginResponse&gt; apply(LoginResponse response) throws Exception {<br>                    pref.setToken(&quot;Bearer &quot; + response.getAccessToken());<br>                    pref.setRefreshToken(response.getRefreshToken());<br>                    pref.setNombre(response.getPerfil().getNombre());<br>                    pref.setApellido(response.getPerfil().getApellido());<br>                    pref.setTelefono(response.getPerfil().getCelular());<br>                    pref.setEmail(response.getPerfil().getEmail());<br>                    return Observable.<em>just</em>(response);<br>                }<br>            });<br>    }</pre><pre>    @Override<br>    public User getUser() {<br>        return new User(0,pref.getNombre(),pref.getApellido(),pref.getTelefono(),pref.getEmail());<br>    }</pre><pre>    @Override<br>    public boolean logout() {<br>        pref.limpiarSP();<br>        return true;<br>    }</pre><pre>    @Override<br>    public boolean isUserLogged() {<br>        if (!pref.getToken().isEmpty()) return true;<br>        else return false;<br>    }<br>}</pre><p>Una vez ejecutado el login, si los datos son correctos, vemos que procedemos a guardar estos en nuestro sharedPreferences, esto lo hacemos porque si observamos en nuestro LoginContract, contamos con otros métodos para consultar cuando la app se inicia, si ya contamos con alguna cuenta logueada.</p><p>En caso de ocurrir algún error, el subscriptor (nuestro presenter) tiene la capacidad de tomarlo y poder operar con el. De eso se encarga nuestro método “handleApiError()”, que es un método base para todos nuestros presenters que serán subscriptores.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709db2fbf9fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desarrollo Android — Parte 1 (Patrones — Testing — Integración continua con Jenkins)]]></title>
            <link>https://medium.com/@abanico_sa/desarrollo-android-parte-1-patrones-testing-integraci%C3%B3n-continua-con-jenkins-c586a4a76a2c?source=rss-912ddca67b67------2</link>
            <guid isPermaLink="false">https://medium.com/p/c586a4a76a2c</guid>
            <category><![CDATA[mpv]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Abanico SA]]></dc:creator>
            <pubDate>Fri, 26 Apr 2019 18:58:36 GMT</pubDate>
            <atom:updated>2019-04-26T19:11:03.994Z</atom:updated>
            <content:encoded><![CDATA[<h3>Desarrollo Android — Parte 1 (Patrones — Testing — Integración continua con Jenkins)</h3><h3>1) MVP EN ANDROID</h3><p>En este artículo, vamos a mostrar como crear una aplicación de Android con Java, en el cual simulamos el juego de “Piedra, papel o tijera” usando el patrón de arquitectura denominado MVP (Modelo-Vista-Presentador).</p><p>MVP es un patrón arquitectónico que sirve para modelar la capa de presentación del software, esa con la que interactúa el usuario. Lo que hace este patrón es delegar toda la lógica a una entidad llamada “Presentador”, que será la que se encargue de decidir qué se muestra en la vista y actuar ante los eventos del usuario.</p><p>La vista no será más que el punto de interacción con el usuario y, como comentaba, en Android estará representado por una Activity o un Fragment normalmente.</p><p>El modelo es básicamente “todo lo demás”: toda la lógica de negocio, persistencia de datos, conexión con APIS, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/0*bIaOBCUkCAAs_BQZ" /></figure><p><strong>Credit:</strong> <a href="https://www.techyourchance.com/">https://www.techyourchance.com/</a></p><ul><li>Modelo: Esta capa gestiona los datos. Son las clases que llamaríamos de lógica de negocio.</li><li>Vista: Se encarga de mostrar los datos. Aquí se colocan nuestros Fragmentos y Vistas.</li><li>Presentador: Se sitúa entre el modelo y la vista, permitiendo conectar la interfaz gráfica con los datos.</li></ul><p><strong>Las ventajas que nos dá MVP:</strong></p><ul><li>Escribir un código más limpio y semánticamente más correcto (puedes leer un poco sobre Domain Driven Design si te interesan estos temas).</li><li>Hacer tests unitarios más sencillos sin necesidad de mockear el Framework, algo que ya es posible a día de hoy pero que trae muchos problemas inesperados.</li><li>Evitar gran parte de tests de instrumentación: al hacer las vistas tan simples, no necesitamos probar prácticamente nada de lógica en ellas. Es verdad que aún así hay mucha parte de visualización que podríamos verificar con herramientas como Espresso, pero estos tests se pueden limitar a lo estrictamente necesario.</li></ul><p><strong>¿Cómo funcionará nuestra app?</strong></p><ol><li>El usuario presionará sobre el elemento que quiera elegir (piedra, papel o tijera) para empezar el juego.</li><li>El Presentador recibe la opción elegida por el usuario y llama al modelo para que empiece con el juego</li><li>El modelo comienza el juego de manera online (request al servidor ayudado con la librería de Volley) u offline (dependiendo de si contamos o no con conexión a internet) y devuelve un objeto con el resultado del juego</li><li>Si todo ha ido bien, el Presentador muestra en el activity la elección que realizó el oponente y el resultado del juego (victoria, empate o derrota).</li></ol><p>El código completo más algunos recursos está disponible en github. Por favor, echa un vistazo a “Link referenciando a github”.</p><p>Vamos a empezar agregando las dependencias para la librería de Voley en nuestro gradle de la app con la siguiente línea:</p><pre>implementation ‘com.android.volley:volley:1.1.1’.</pre><p>Procedemos a sincronizar el proyecto.</p><p>Ahora diseñaremos el activity de la siguiente manera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*apcXIlnjpyaBx3B9" /></figure><p><strong>Activity_main.xml</strong></p><pre>&lt;?xml version=”1.0&quot; encoding=”utf-8&quot;?&gt;</pre><pre>&lt;android.support.constraint.ConstraintLayout</pre><pre>xmlns:android=”http://schemas.android.com/apk/res/android&quot;</pre><pre>xmlns:app=”http://schemas.android.com/apk/res-auto&quot;</pre><pre>xmlns:tools=”http://schemas.android.com/tools&quot;</pre><pre>android:layout_width=”match_parent”</pre><pre>android:layout_height=”match_parent”</pre><pre>tools:context=”.view.MainActivity”&gt;</pre><pre>&lt;Button</pre><pre>android:id=”@+id/btn_piedra”</pre><pre>android:layout_width=”157dp”</pre><pre>android:layout_height=”112dp”</pre><pre>android:layout_marginTop=”20dp”</pre><pre>android:background=”@drawable/piedra_efecto”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintHorizontal_bias=”0.502&quot;</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/tv_juego” /&gt;</pre><pre>&lt;Button</pre><pre>android:id=”@+id/btn_papel”</pre><pre>android:layout_width=”157dp”</pre><pre>android:layout_height=”112dp”</pre><pre>android:layout_marginTop=”8dp”</pre><pre>android:background=”@drawable/papel_efecto”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintHorizontal_bias=”0.502&quot;</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/btn_piedra” /&gt;</pre><pre>&lt;Button</pre><pre>android:id=”@+id/btn_tijera”</pre><pre>android:layout_width=”157dp”</pre><pre>android:layout_height=”112dp”</pre><pre>android:layout_marginTop=”8dp”</pre><pre>android:background=”@drawable/tijera_efecto”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintHorizontal_bias=”0.502&quot;</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/btn_papel” /&gt;</pre><pre>&lt;TextView</pre><pre>android:id=”@+id/tv_juego”</pre><pre>android:layout_width=”wrap_content”</pre><pre>android:layout_height=”wrap_content”</pre><pre>android:layout_marginTop=”6dp”</pre><pre>android:text=”@string/piedra_papel_o_tijera”</pre><pre>android:textAlignment=”center”</pre><pre>android:textAllCaps=”false”</pre><pre>android:textSize=”24sp”</pre><pre>android:textStyle=”bold|italic”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toTopOf=”parent” /&gt;</pre><pre>&lt;TextView</pre><pre>android:id=”@+id/tv_resultado”</pre><pre>android:layout_width=”wrap_content”</pre><pre>android:layout_height=”wrap_content”</pre><pre>android:layout_marginTop=”16dp”</pre><pre>android:hint=”@string/resultado”</pre><pre>android:text=”@string/resultado”</pre><pre>android:textAlignment=”center”</pre><pre>android:textSize=”18sp”</pre><pre>android:textStyle=”bold”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/tv_oponente” /&gt;</pre><pre>&lt;TextView</pre><pre>android:id=”@+id/tv_oponente”</pre><pre>android:layout_width=”wrap_content”</pre><pre>android:layout_height=”wrap_content”</pre><pre>android:layout_marginTop=”14dp”</pre><pre>android:hint=”@string/oponente”</pre><pre>android:text=”@string/oponente”</pre><pre>android:textAlignment=”center”</pre><pre>android:textSize=”18sp”</pre><pre>android:textStyle=”bold”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/btn_tijera” /&gt;</pre><pre>&lt;ProgressBar</pre><pre>android:id=”@+id/progressBar10&quot;</pre><pre>style=”?android:attr/progressBarStyle”</pre><pre>android:layout_width=”wrap_content”</pre><pre>android:layout_height=”wrap_content”</pre><pre>android:layout_marginStart=”8dp”</pre><pre>android:layout_marginTop=”2dp”</pre><pre>android:layout_marginEnd=”8dp”</pre><pre>android:layout_marginBottom=”2dp”</pre><pre>android:visibility=”gone”</pre><pre>app:layout_constraintBottom_toBottomOf=”parent”</pre><pre>app:layout_constraintEnd_toEndOf=”parent”</pre><pre>app:layout_constraintStart_toStartOf=”parent”</pre><pre>app:layout_constraintTop_toBottomOf=”@+id/tv_resultado” /&gt;</pre><pre>&lt;/android.support.constraint.ConstraintLayout&gt;</pre><p>Se puede observar que en los botones, en su background, tenemos un archivo que se llama “piedra_efecto”,”tijera_efecto” y ”papel_efecto”, estos son archivos xml que usamos para darle un efecto al momento de ser presionados esos botones.</p><p><strong>papel_efecto.xml</strong></p><pre>&lt;?xml version=”1.0&quot; encoding=”utf-8&quot;?&gt;</pre><pre>&lt;selector xmlns:android=”http://schemas.android.com/apk/res/android&quot;&gt;</pre><pre>&lt;item android:drawable=”@drawable/seleccion”</pre><pre>android:state_pressed=”true”/&gt;</pre><pre>&lt;item android:drawable=”@drawable/papel”/&gt;</pre><pre>&lt;/selector&gt;</pre><p><strong>piedra_efecto.xml</strong></p><pre>&lt;selector xmlns:android=”http://schemas.android.com/apk/res/android&quot;&gt;</pre><pre>&lt;item android:drawable=”@drawable/seleccion”</pre><pre>android:state_pressed=”true”/&gt;</pre><pre>&lt;item android:drawable=”@drawable/piedra”/&gt;</pre><pre>&lt;/selector&gt;</pre><p><strong>tijera_efecto.xml</strong></p><pre>&lt;?xml version=”1.0&quot; encoding=”utf-8&quot;?&gt;</pre><pre>&lt;selector xmlns:android=”http://schemas.android.com/apk/res/android&quot;&gt;</pre><pre>&lt;item android:drawable=”@drawable/seleccion”</pre><pre>android:state_pressed=”true”/&gt;</pre><pre>&lt;item android:drawable=”@drawable/tijera”/&gt;</pre><pre>&lt;/selector&gt;</pre><p>Recuerda que las imágenes puede descargarlas desde gitHub, o puede usar unas propias para realizar este ejemplo.</p><p><strong>Paquetes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*Fwz7QYloHDv84Uk-" /></figure><p><strong>Entity</strong></p><p>Aquí colocamos las entidades de nuestra app, en este caso solo contamos con la clase “ResultadoJuego” que la usaremos para crear el objeto que tendrá la elección del oponente y el resultado final de la partida jugada:</p><p><strong>ResultadoJuego.java</strong></p><pre>public class ResultadoJuego {</pre><pre>String eleccionOponente;</pre><pre>String resultadoFinal;</pre><pre>public ResultadoJuego() {</pre><pre>}</pre><pre>public String getEleccionOponente() {</pre><pre>return eleccionOponente;</pre><pre>}</pre><pre>public String getResultadoFinal() {</pre><pre>return resultadoFinal;</pre><pre>}</pre><pre>public void setEleccionOponente(String eleccionOponente) {</pre><pre>this.eleccionOponente = eleccionOponente;</pre><pre>}</pre><pre>public void setResultadoFinal(String resultadoFinal) {</pre><pre>this.resultadoFinal = resultadoFinal;</pre><pre>}</pre><pre>}</pre><p><strong>Utils</strong></p><p>En este paquete vamos a colocar nuestros métodos, Strings estáticas globales y otros elementos que sean comunes para toda la app, en nuestro caso solo usaremos una clase llama “EndPoint” que cuenta con el String de la dirección donde haremos nuestro request con Volley.</p><p><strong>EndPoint.java</strong></p><pre>public class EndPoint {</pre><pre>public static final String DIRECCION_IP = “http://farmear.net/Farmear/games/miniTest.php&quot;;</pre><pre>}</pre><p>Puedes usar la misma dirección para probar tu app, o puede subir el archivo .php y genera tu propio String para realizar el request. Este es el código que contiene el archivo “miniTest.php”.</p><pre>&lt;?php</pre><pre>$json=array();</pre><pre>$eleccion = $_POST[“eleccion”];</pre><pre>$eleccionCpu = rand (1,3);</pre><pre>if ($eleccion &gt;=1 &amp;&amp; $eleccion&lt;=3) {</pre><pre>if ($eleccion ==1) {</pre><pre>if ($eleccionCpu==1) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAN EMPATADO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==2) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS PERDIDO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==3) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS GANADO!!”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}</pre><pre>}elseif ($eleccion ==2) {</pre><pre>if ($eleccionCpu==1) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS GANADO!!”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==2) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAN EMPATADO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==3) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS PERDIDO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}</pre><pre>}elseif ($eleccion ==3) {</pre><pre>if ($eleccionCpu==1) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS PERDIDO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==2) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAS GANADO!!”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}elseif ($eleccionCpu==3) {</pre><pre>$result[“oponente”]=$eleccionCpu;</pre><pre>$result[“resultado”]= “HAN EMPATADO”;</pre><pre>$json[‘datos’][]=$result;</pre><pre>echo json_encode($json);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>else{echo “Ha ocurrido un error”;}</pre><pre>?&gt;</pre><p><strong>NetWorking</strong></p><p>Este es un paquete personalizado para realizar los request al servidor usando Volley. Puede usarlo para el ejemplo o puede cambiarlo por un propio que tengas.</p><p><strong>Interfaces</strong></p><p>Contiene todas las interfaces que hay en la app. Nosotros vamos a tener una interface llamada “IJugarPPT” que tendrán los métodos que implementaremos en cada clase del MVP para lograr la comunicación entre ellos. Si son muchos los métodos en cada clase, podríamos implementar una interfaz por cada una de las capas del MVP, en este caso son pocas así que haremos una sola interface donde colocaremos dentro las interfaces de la vista, presentador y modelo.</p><p><strong>IJugarPPT.java</strong></p><pre>public interface IJugarPPT {</pre><pre>interface View{</pre><pre>void mostrarResultado(ResultadoJuego resultadoJuego);</pre><pre>void showProgressBar();</pre><pre>}</pre><pre>interface Presenter{</pre><pre>void mostrarResultadoOnline(ResultadoJuego resultadoJuego);</pre><pre>void mostrarResultadoOffline(ResultadoJuego resultadoJuego);</pre><pre>void comenzarJuego(int eleccion, Context ctx);</pre><pre>}</pre><pre>interface Model{</pre><pre>void comenzarJuego(int eleccion, Context ctx);</pre><pre>}</pre><pre>}</pre><p><strong>View</strong></p><p>Aquí van nuestras activities y fragments, vamos a crear instancias de nuestros elementos y hacer la referencia correspondiente con el layout del activity_main.xml</p><pre>Button btnPiedra, btnPapel, btnTijera;</pre><pre>TextView tvOponente, tvResultado;</pre><pre>ResultadoJuego rJuego;</pre><pre>ProgressBar progressBar;</pre><pre>btnPapel = findViewById(R.id.btn_papel);</pre><pre>btnPiedra = findViewById(R.id.btn_piedra);</pre><pre>btnTijera = findViewById(R.id.btn_tijera);</pre><pre>tvResultado = findViewById(R.id.tv_resultado);</pre><pre>tvOponente = findViewById(R.id.tv_oponente);</pre><pre>progressBar = findViewById(R.id.progressBar10);</pre><pre>rJuego = new ResultadoJuego();</pre><p>Esta vista necesita contacto con el presentador, para eso hacemos la instancia del Presentador que se va a encargar de manejar todos los eventos que ocurran entre el usuario y la app.</p><pre>private IJugarPPT.Presenter presenter;</pre><p>El presentador necesita la vista para ser inicializado.</p><pre>presenter = new JugarPresenter(this);</pre><p>El MainActivity.java tiene que implementar todos los metodos de la vista, asi q a la clase le agregamos:</p><pre>implements IJugarPPT.View</pre><p>El codigo completo sería:</p><p><strong>MainActivity.java</strong></p><pre>public class MainActivity extends AppCompatActivity implements IJugarPPT.View {</pre><pre>Button btnPiedra, btnPapel, btnTijera;</pre><pre>TextView tvOponente, tvResultado;</pre><pre>private IJugarPPT.Presenter presenter;</pre><pre>ResultadoJuego rJuego;</pre><pre>ProgressBar progressBar;</pre><pre>@Override</pre><pre>protected void onCreate(Bundle savedInstanceState) {</pre><pre>super.onCreate(savedInstanceState);</pre><pre>setContentView(R.layout.activity_main);</pre><pre>btnPapel = findViewById(R.id.btn_papel);</pre><pre>btnPiedra = findViewById(R.id.btn_piedra);</pre><pre>btnTijera = findViewById(R.id.btn_tijera);</pre><pre>tvResultado = findViewById(R.id.tv_resultado);</pre><pre>tvOponente = findViewById(R.id.tv_oponente);</pre><pre>progressBar = findViewById(R.id.progressBar10);</pre><pre>rJuego = new ResultadoJuego();</pre><pre>presenter = new JugarPresenter(this);</pre><pre>btnPiedra.setOnClickListener(new View.OnClickListener() {</pre><pre>@Override</pre><pre>public void onClick(View v) {</pre><pre>presenter.comenzarJuego(1,getApplicationContext());</pre><pre>}</pre><pre>});</pre><pre>btnPapel.setOnClickListener(new View.OnClickListener() {</pre><pre>@Override</pre><pre>public void onClick(View v) {</pre><pre>presenter.comenzarJuego(2, getApplicationContext());</pre><pre>}</pre><pre>});</pre><pre>btnTijera.setOnClickListener(new View.OnClickListener() {</pre><pre>@Override</pre><pre>public void onClick(View v) {</pre><pre>presenter.comenzarJuego(3,getApplicationContext());</pre><pre>}</pre><pre>});</pre><pre>}</pre><pre>@Override</pre><pre>public void showProgressBar(){</pre><pre>progressBar.setVisibility(View.VISIBLE);</pre><pre>}</pre><pre>@Override</pre><pre>public void mostrarResultado(ResultadoJuego resultadoJuego) {</pre><pre>rJuego.setEleccionOponente(resultadoJuego.getEleccionOponente());</pre><pre>rJuego.setResultadoFinal(resultadoJuego.getResultadoFinal());</pre><pre>progressBar.setVisibility(View.GONE);</pre><pre>tvOponente.setText(resultadoJuego.getEleccionOponente());</pre><pre>tvResultado.setText(resultadoJuego.getResultadoFinal());</pre><pre>}</pre><pre>}</pre><p>Entonces al momento de que el presentador llame al método showProgressBar(), hará que la vista se actualice y muestre el progressBar que tiene dentro, y otro método para mostrar el resultado final de la partida jugada.</p><p>Dentro de los eventos OnClick de los botones podemos ver el llamado al presentador para disparar su método que es comenzarJuego(), el cual tiene como parámetro el valor de la elección que eligió el usuario (1=Piedra, 2=Papel y 3=Tijera).</p><p><strong>Presenter</strong></p><p>En este paquete tenemos una clase llamada JugarPresenter, el presentador va a ser el encargado mover los hilos de todo este equipo, se va a parar en el medio entre vista y modelo y va a distribuir y determinar los elementos que deben mostrarse y los métodos a ejecutarse.</p><p><strong>JugarPresenter.java</strong></p><pre>public class JugarPresenter implements IJugarPPT.Presenter{</pre><pre>private IJugarPPT.View view;</pre><pre>private IJugarPPT.Model model;</pre><pre>public JugarPresenter(IJugarPPT.View view){</pre><pre>this.view = view;</pre><pre>model = new JugarModel(this);</pre><pre>}</pre><pre>@Override</pre><pre>public void mostrarResultadoOnline(ResultadoJuego resultadoJuego) {</pre><pre>if (view!=null){</pre><pre>view.mostrarResultado(resultadoJuego);</pre><pre>}</pre><pre>}</pre><pre>@Override</pre><pre>public void mostrarResultadoOffline(ResultadoJuego resultadoJuego) {</pre><pre>if (view!=null){</pre><pre>view.mostrarResultado(resultadoJuego);</pre><pre>}</pre><pre>}</pre><pre>@Override</pre><pre>public void comenzarJuego(int eleccion, Context ctx) {</pre><pre>if (view!=null){</pre><pre>view.showProgressBar();</pre><pre>model.comenzarJuego(eleccion,ctx);</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Necesita la vista en su constructor, como lo habíamos mencionado previamente, y además, por cada instancia creada, vamos a realizar una instancia a la clase model, para poder ejecutar sus métodos, dentro de sus métodos (que son los implementados por la interfaz IJugarPPT.Presenter) es donde validamos que tenemos una vista, para mostrar ahí los cambios o respuestas que puedan llegar por parte del modelo.</p><p><strong>Model</strong></p><p>Acá van nuestros models, los que contienen conexiones, lógica de datos y otros procesos completamente diferenciado y separado de lo que es el diseño de la app. Nuestro modelo llamado “JugarModel” (que tendrá su presentador y sus métodos que vienen de la interface IJugarPPT.Model) tiene en este caso variables como el método que usaremos para el request, la url, los parámetros que enviaremos, etc.</p><p>Gracias a nuestro paquete NetWorking, llamamos a la instancia de nuestro NetworkManager y ejecutamos su función “makeStringRequest” pasando los parametros que necesita. El resultado que devuelve este request es lo que usaremos.</p><p>Ejemplo de devolución en el getResult():</p><p>{“datos”:[{“oponente”:1,”resultado”:”HAS PERDIDO”}]}</p><p>Este json que nos devuelve el request es lo que vamos a parsear para guardarlo dentro de un objeto “ResultadoJuego” (para esto nos sirve nuestra clase creada en el paquete entity) y lo pasaremos al presentador para que se encargue de llevarlo hasta la vista y pueda mostrarlo como resultado.</p><p><strong>JugarModel.java</strong></p><pre>public class JugarModel implements IJugarPPT.Model {</pre><pre>private IJugarPPT.Presenter presenter;</pre><pre>private int eleccionClass,method;</pre><pre>private String url;</pre><pre>Map&lt;String,String&gt; params;</pre><pre>private Context contextClass;</pre><pre>public JugarModel(IJugarPPT.Presenter presenter){</pre><pre>this.presenter = presenter;</pre><pre>}</pre><pre>@Override</pre><pre>public void comenzarJuego(int eleccion, Context ctx) {</pre><pre>eleccionClass = eleccion;</pre><pre>contextClass = ctx;</pre><pre>url = EndPoint.DIRECCION_IP;</pre><pre>method = Request.Method.POST;</pre><pre>params = new HashMap&lt;&gt;();</pre><pre>params.put(“eleccion”, String.valueOf(eleccionClass));</pre><pre>if(StateNetwork.compruebaConexion(contextClass)){</pre><pre>NetworkManager.getInstance().makeStringRequest(params,method, url, contextClass, new NetworkCustomListener&lt;String&gt;() {</pre><pre>@Override</pre><pre>public void getResult(String result) {</pre><pre>if (!result.isEmpty())</pre><pre>{</pre><pre>try{</pre><pre>JSONObject jsonObject = new JSONObject(result);</pre><pre>JSONArray jsonArray = jsonObject.optJSONArray(“datos”);</pre><pre>JSONObject json;</pre><pre>json = jsonArray.getJSONObject(0);</pre><pre>int eleecionOponente = json.optInt(“oponente”);</pre><pre>String resultadoFinal = json.optString(“resultado”);</pre><pre>ResultadoJuego resJuego= new ResultadoJuego();</pre><pre>if (eleecionOponente==1){</pre><pre>resJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PIEDRA”);</pre><pre>}else if (eleecionOponente==2){</pre><pre>resJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PAPEL”);</pre><pre>}else if (eleecionOponente==3){</pre><pre>resJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ TIJERA”);</pre><pre>}</pre><pre>resJuego.setResultadoFinal(“RESULTADO: “ + resultadoFinal);</pre><pre>presenter.mostrarResultadoOnline(resJuego);</pre><pre>}catch (JSONException e){</pre><pre>e.printStackTrace();</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>});</pre><pre>}else {</pre><pre>ResultadoJuego resultadoJuego= new ResultadoJuego();</pre><pre>int numero = (int) (Math.random() * 3) + 1;</pre><pre>if (eleccion ==1){</pre><pre>if (numero==1){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PIEDRA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS EMPATADO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==2){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PAPEL”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS PERDIDO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==3){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ TIJERA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS GANADO!”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}</pre><pre>}else if (eleccion ==2){</pre><pre>if (numero==1){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PIEDRA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS GANADO!”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==2){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PAPEL”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS EMPATADO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==3){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ TIJERA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS PERDIDO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}</pre><pre>}else if (eleccion ==3){</pre><pre>if (numero==1){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PIEDRA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS PERDIDO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==2){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ PAPEL”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS GANADO!”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}else if (numero==3){</pre><pre>resultadoJuego.setEleccionOponente(“TU OPONENTE ELIGIÓ TIJERA”);</pre><pre>resultadoJuego.setResultadoFinal(“RESULTADO: HAS EMPATADO”);</pre><pre>presenter.mostrarResultadoOffline(resultadoJuego);</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Se puede observar que previo a realizar un request tenemos un if que se encarga de averiguar si contamos o no con una conexión a internet.</p><p>En caso de no tener esa conexión, se va a ejecutar el juego de igual manera, pero esta vez realizando todo el cálculo dentro del teléfono, de manera local en el dispositivo, lo cual dispara otro método del presentador, que sería mostrar el resultado pero trabajando de manera offline.</p><p>Aquí se puede observar lo mucho que nos ayuda este patrón de arquitectura y de poder descomponer de esta manera nuestra app (imaginense realizar más caminos alternativos en el caso de poder decir que los datos ingresados son inválido como un ejemplo más). Esto nos puede ayudar demasiado como se les mencionó anteriormente al momento de empezar con los test unitarios en Android (tema que veremos en otro artículo) y claramente nos da una mano a nosotros para mantener un código mucho más legible y limpio.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c586a4a76a2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Rekognition in Android]]></title>
            <link>https://medium.com/how-to-integrate-aws-rekognition-in-android/aws-rekognition-in-android-9d16f16d591c?source=rss-912ddca67b67------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d16f16d591c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[amazon-rekognition]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Abanico SA]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 02:01:26 GMT</pubDate>
            <atom:updated>2019-04-26T19:13:26.703Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In this article we are going to build an Android application using Java, that simulates a login using facial recognition by checking your DNI’s (personal identification card here in Argentina) face with a video of ourselves that we provide to the application.</p><p>The flow is:</p><ol><li>Scan the PDF 417 code in the DNI</li><li>Then we need to take a picture from the DNI’s front</li><li>Another picture from the DNI’s back</li><li>Take a video from our face</li></ol><p>We are going to use other AWS Services like:</p><ul><li>AWS Rekognition service in order to do facial recognition, but we’ll have to use other services like AWS Cognito, to give you secure access and the permissions to our application to use the AWS services.</li><li>AWS S3 to store photos and videos that will be analyzed by Rekognition.<br>It is very important to choose the same region for all the services that we will use in AWS, in our case we will choose the US East region (N. Virginia).<br>We will not start the application from scratch, but we will take as a skeleton of ours the following example that AWS provides us on its website. [1]</li></ul><p><strong>S3TransferUtilitySample </strong><br>is a sample application to upload and download files from our smartphone to a bucket in S3. We will adapt it so that it only uploads the files to S3. These files will be two photos and one video.</p><p>This application is not intended to be the best implementation of rekognition nor the best encoded, it is a proof of concept where all contributions to improve it will be welcome.</p><p><strong>Step 1) Configure AWS services</strong></p><p><strong>1.1) Create a identity pool</strong></p><p>We will create an Identity Pool in AWS Cognito, for this we go to the AWS Cognito administration panel and click on Manage Identity Pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*btDbRwG2UNKKmuYs" /></figure><p>Click Create new Identity pool button on the top left of the console.</p><p>Give a name for the Identity pool and check Enable access to unauthenticated identities under the Unauthenticated Identities section, click Create pool button on the bottom right.</p><p>We will call “tutorialpool” and check the box “Enable access to unauthenticated identities”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LC-BTvyRTqiS1xaR" /></figure><p>Click in Create Pool</p><p>To enable Cognito Identities to access your resources, expand the View Details section to see the two roles that are to be created. Make a note of the unauth role whose name is of the form Cognito_&lt;IdentityPoolName&gt;Unauth_Role.</p><p>We take note of the name that the unauthenticated identities that would like to access Cognito will use. In this case the name is “Cognito_tutorialpoolUnauth_Role”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*gxABrKcF1NgODjKd" /></figure><p>Now click Allow button in the bottom right of the console.</p><p>Under Get AWSCredentials section, in the code snippet to create CognitoCachingCredentialsProvider , find the Identity pool ID and the AWS region and make note of them. You will need to add to the sample application later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*DxaZogy92M9yWf1M" /></figure><p>Copy Identity pool ID: “us-east-1:kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf”</p><p>and regions: “Regions.US_EAST_1”, we will need them later. Finally we press on Go To Dashboard.</p><p><strong>1.2) Set up permissions</strong></p><p>Go to Amazon IAM Console and select “Roles”.</p><p>Select the unauth role you just created in step 1, which is of the form Cognito_&lt;IdentityPoolName&gt;Unauth_Role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*2-Q-h5RIEVSv7M3Y" /></figure><p>Select Attach Policy, then find AmazonS3FullAccess and attach it it to the role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/0*k8Nqifg0EMblEs4y" /></figure><p>Note: This will grant users in the identity pool full access to all buckets and operations in S3. In a real app, you should restrict users to only have access to the resources they need.</p><p>We look for the following services and we give you permission because we will use them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8qmapeekEIYFiUmB" /></figure><p>For now we leave them like this, we will explain each one of them as we use them.</p><p><strong>1.3) Create a bucket</strong></p><p>Go to Amazon S3 Console and click Create bucket.</p><p>Enter a name for the bucket that is DNS-compliant.</p><p>Choose the region that you want the bucket to be created.</p><p>Click Create. Note the name and the region of the bucket that was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aLKGecJCDRbTNDP5" /></figure><p>Click next, next, and next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HsHIq0Es1nio0-xd" /></figure><p>Finally we press on Create bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ywlnv5C1vnqkeIjH" /></figure><p><strong>Paso 2) Import the sample project S3TransferUtilitySample<br></strong>Import the sample as Android project into your IDE of choice.<br>Open awsconfiguration.json in src/com/amazonaws/demo/s3transferutility directory.<br>Update PoolId with the ID of the Cognito Identity Pool created in Step-1.<br>Update Region with the region of the Cognito Identity Pool created from Step-1. For example, us-east-1. The Region column in Amazon Cognito Identity Regions represents the region string.<br>Update Bucket with the name of the S3 Bucket created in Step-3.<br>Update Region with the region of the S3 Bucket created from Step-3. For example, us-east-1. The Regioncolumn in Aamazon S3 Regions represents the region string.</p><p>Contents of the file awsconfiguration.json:</p><pre>{<br> “Version”: “1.0”,<br> “IdentityManager”: {<br> “Default”: {}<br> },<br>“CredentialsProvider”: {<br> “CognitoIdentity”: {<br> “Default”: {<br> “PoolId”: “us-east-1:417345274537435hr4r4sdf34fsc”,<br> “Region”: “us-east-1”<br> }<br> }<br>},<br> “S3TransferUtility”: {<br> “Default”: {<br> “Bucket”: “tutorialcubo”,<br> “Region”: “us-east-1”<br> }<br> }<br>}</pre><p><strong>Paso 5) Integrating with other functionalities</strong></p><p>First we will scan the PDF code 417 of the DNI based on an example of google samples. [2]<br>Then we will modify it to give the user control when taking the photo and the video immediately after scanning the PDF code 417, for which we will be guided of the excellent work of TheAppGuruz. [3]</p><p>Inside Constants.java we add:</p><pre>public static final String ACCESS_KEY = “kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf”;<br>public static final String SECRET_KEY = “kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf”;</pre><pre>public static String TOPICARN=”arn:aws:sns:us-east-1:kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf”;<br>public static String ROLEARN=”arn:aws:iam::kjdfkjdfbkjds/Cognito_rekognitionandroidUnauth_Role”;</pre><pre>public class Constants {<br> public static final String COGNITO_POOL_ID = “us-east-1:kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf”;<br> public static final String COGNITO_POOL_REGION = “us-east-1”;<br> public static final String BUCKET_NAME = “tutorialcubo”;<br> public static final String BUCKET_REGION = “us-east-1”;<br> public static final String ACCESS_KEY = “AkjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngfA”;<br> public static final String SECRET_KEY = “4kjdfkjdfbkjdsbdsfkjdskjdfsbkjfdabnkjfdgngf3+”;<br> public static String TOPICARN=”arn:aws:sns:us-east-1:435435345345noticias”;<br> public static String ROLEARN=”arn:aws:iam::434543599345:role/Cognito_rekognitionandroidUnauth_Role”;<br>}</pre><p>Inside build.gradle add:</p><pre>dependencies {<br> def aws_version = “2.11.+”<br> implementation “com.amazonaws:aws-android-sdk-s3:$aws_version”<br> implementation(“com.amazonaws:aws-android-sdk-mobile-client:$aws_version”) { transitive = true }<br> implementation ‘com.android.support.test.espresso:espresso-core:3.0.2’,</pre><pre>{<br> exclude group: ‘com.android.support’, module: ‘support-annotations’<br> }<br> implementation ‘com.android.support.test:rules:1.0.2’<br> implementation “com.android.support:support-compat:28.0.0”<br> implementation ‘com.android.support.test.uiautomator:uiautomator-v18:2.0.0’<br> implementation ‘com.amazonaws:aws-android-sdk-rekognition:2.7.0’<br> implementation ‘com.android.support:appcompat-v7:28.0.0’<br> implementation ‘com.android.support.constraint:constraint-layout:1.1.3’<br> implementation ‘com.google.android.gms:play-services-vision:11.4.2’<br> implementation ‘com.android.support:design:28.0.0’<br> implementation ‘com.amazonaws:aws-android-sdk-s3:2.7.+’<br> implementation ‘com.amazonaws:aws-android-sdk-rekognition:2.7.0’<br> implementation ‘com.amazonaws:aws-android-sdk-sns:2.7.0’<br> implementation ‘com.amazonaws:aws-android-sdk-sqs:2.7.0’<br>}</pre><p>Inside manifest we add:</p><pre>&lt;uses-permission android:name=”android.permission.CAMERA” /&gt;<br> &lt;uses-permission android:name=”android.permission.INTERNET” /&gt;<br> &lt;uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” /&gt;<br> &lt;uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE” /&gt;<br> &lt;uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” /&gt;</pre><pre>.</pre><pre>.</pre><pre>.</pre><pre>&lt;provider<br> android:name=”android.support.v4.content.FileProvider”<br> android:authorities=”com.amazonaws.demo.s3transferutility.fileprovider”<br> android:exported=”false”<br> android:grantUriPermissions=”true”&gt;<br> &lt;meta-data<br> android:name=”android.support.FILE_PROVIDER_PATHS”<br> android:resource=”@xml/file_paths”</pre><pre>/&gt;</pre><pre>&lt;/provider&gt;</pre><p><strong>Step 6) Explaining the functionality and workflow that we will create</strong></p><p>Inside InicioActitivy</p><p>The application starts at StartActivity and calls BarcodeCaptureActivity when the “next” button is pressed. It does not do anything else, the idea is to be the splashActivity, or to indicate the general instructions to the user before starting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Vwq3XdI7q9mJxLcT" /></figure><p>Inside BarcodeCaptureActivity</p><p>Open the camera application and scan the PDF code 417 of the DNI, when you scan it, call FotoActivity and pass it the code information.</p><p>Inside FotoActivity</p><p>Open the camera application for the user to take a picture of the front of the ID and after the photo is taken automatically upload to the S3 bucket, without user intervention, after taking the photo, open the camera application again take another picture of the back of the DNI, which is also uploaded to the same S3 bucket after the user takes the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*NRO1VOnKqPBox46w" /></figure><p>Call the method llamada() where you create the collection of rekognition with the name of the first photograph we took, which corresponds to the front of the DNI that also has the face that will be added to this collection. Create the collection and call the DataActivity activity and send it the information of the PDF code 417, the name of the photo on the front of the DNI and its route on the cell phone.</p><p><strong>Step 7) Create a collection in AWS Rekognition</strong></p><p>A collection is a Rekonition concept, which is where the parameters extracted from the images that are in the S3 bucket will be saved.<br>To create this collection can only be done from the Android API, or from the CLI (command line interface), it can not be done in a more friendly way with the AWS control panel as with other services.<br>So in the next steps we will modify our App, so that the collection is created with the name of the photo that we take in front of the ID without the extension “.jpg”<br>The implementation is in the method createcollection (name), where name is the name of the photo without the extension. We will guide you through this guide with a sample code. [5]</p><pre>public void crearcoleccion(String name) {<br> AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);<br> AmazonRekognition rekognitionClient = new AmazonRekognitionClient(credentials);<br> rekognitionClient.setRegion(Region.getRegion(Regions.US_EAST_1));<br> CreateCollectionRequest request = new CreateCollectionRequest()<br> .withCollectionId(name);<br> CreateCollectionResult createCollectionResult = rekognitionClient.createCollection(request);<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*uP7K6GHUXW7HWbc_" /></figure><p><strong>Step 8) Using DetectFacesRequest from AWS Rekognition</strong></p><p>Inside DataActivity we will use the first function of rekognition, which will allow us to detect a face in a photo. We will use it to identify the face of the ID and then we will cut it so that it only shows the face and not the rest of the ID.<br>We will guide you through this guide with a sample code provided by AWS. [4]<br>With the information provided by the PDF code 417 we will calculate the expiration date of the DNI and the cuit / cuil to show them together with the other data. The implementation is in the detectostro() method.</p><pre>public void detectarostro(){<br> AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);<br> AmazonRekognition rekognitionClient = new AmazonRekognitionClient(credentials);<br> rekognitionClient.setRegion(Region.getRegion(Regions.US_EAST_1));<br> DetectFacesRequest request = new DetectFacesRequest()<br> .withImage(new Image()<br> .withS3Object(new S3Object()<br> .withName(nombre)<br> .withBucket(bucket)))<br> .withAttributes(String.valueOf(Attribute.ALL));</pre><pre>try {<br> DetectFacesResult result = rekognitionClient.detectFaces(request);<br> List&lt;FaceDetail&gt; faceDetails = result.getFaceDetails();<br> for (FaceDetail face : faceDetails) {<br> if (request.getAttributes().contains(“ALL”)) {<br> if(bmImg!=null) {<br> height = bmImg.getHeight();<br> width = bmImg.getWidth();<br> }<br> ShowBoundingBoxPositions(height,<br> width,<br> face.getBoundingBox(),<br> “ROTATE_0”);<br> } else {</pre><pre>}<br> }<br> } catch (Error e) {<br> e.printStackTrace();<br> }<br> }</pre><p><strong>Step 9) Add a face to a collection</strong></p><p>Then we will call the method agrecara () where from the faces that it detects in the front photo of the DNI it will add it to the collection that we created in the previous activity.[6]</p><pre>public void agregacara() {<br> AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);<br> AmazonRekognition rekognitionClient = new AmazonRekognitionClient(credentials);<br> rekognitionClient.setRegion(Region.getRegion(Regions.US_EAST_1));<br> Image image = new Image()<br> .withS3Object(new S3Object()<br> .withBucket(bucket)<br> .withName(nombre));<br> IndexFacesRequest indexFacesRequest = new IndexFacesRequest()<br> .withImage(image)<br> .withCollectionId(coleccionid)<br> .withExternalImageId(nombre)<br> .withDetectionAttributes(“ALL”);<br> IndexFacesResult indexFacesResult = rekognitionClient.indexFaces(indexFacesRequest);<br> List&lt;FaceRecord&gt; faceRecords = indexFacesResult.getFaceRecords();<br> for (FaceRecord faceRecord : faceRecords) {<br> }<br> }</pre><p>Finally we invoke the VideoActivity activity when we press the “next” button. Again the idea is for the user to verify that the information is correct and give him the possibility to continue or repeat the previous process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*LDWQvm0nl3T1dvBZ" /></figure><p>Inside VideoActivity</p><p>Open the camera for the user to film the face and then upload the video to the bucket of S3, also this upload of the file is done without the intervention of the user. Then it calls the method llamada2() that invokes the ResultActivity activity.</p><p><strong>Step 10) Find the face of a video in S3 within a collection of rekognition</strong></p><p>Inside ResultadoActivity</p><p>Within the method comprueba() calls the following methods:</p><pre>public void comprueba(){<br> AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);<br> rek = new AmazonRekognitionClient(credentials);<br> sqs = new AmazonSQSClient(credentials);<br> try {<br> StartFaceSearchCollection(bucket,movie,key1);<br> List&lt;Message&gt; messages=null;<br> int dotLine=0;<br> boolean jobFound=false;<br> GetResultsFaceSearchCollection();<br> } catch (Exception e) {<br> e.printStackTrace();<br> }<br> }</pre><p>StartFaceSearchCollection: receives the name of the bucket, the name of the video and the name of the collection of faces, looks inside the collection of faces for the faces detected in the video. Returns an id of the job that performs rekognition with the results of the analysis.</p><pre>private static void StartFaceSearchCollection(String bucket, String video,String coleccion) throws Exception{<br> String tokencliente = video.split(“\\.”)[0];<br> StartFaceSearchRequest req = new StartFaceSearchRequest()<br> .withCollectionId(coleccion)<br> .withVideo(new Video()<br> .withS3Object(new S3Object()<br> .withBucket(bucket)<br> .withName(video)))<br> .withClientRequestToken(tokencliente+”_”+coleccion)<br> .withJobTag(“DetectingLabels”)<br> .withNotificationChannel(channel);<br> StartFaceSearchResult startPersonCollectionSearchResult = rek.startFaceSearch(req);<br> startJobId=startPersonCollectionSearchResult.getJobId();<br> }</pre><pre>GetResultsFaceSearchCollection: receives the id from the previous job and returns a list with the matching faces.[7]</pre><pre>private void GetResultsFaceSearchCollection() {<br> int bandera=0;<br> GetFaceSearchResult faceSearchResult=null;<br> int maxResults=10;<br> String paginationToken=null;<br> do {<br> if (faceSearchResult !=null){<br> paginationToken = faceSearchResult.getNextToken();<br> }<br> faceSearchResult = rek.getFaceSearch(<br> new GetFaceSearchRequest()<br> .withJobId(startJobId)<br> .withMaxResults(maxResults)<br> .withNextToken(paginationToken)<br> .withSortBy(FaceSearchSortBy.TIMESTAMP)<br> );<br> List&lt;PersonMatch&gt; matches=<br> faceSearchResult.getPersons();<br> for (PersonMatch match: matches) {<br> long milliSeconds=match.getTimestamp();<br> List &lt;FaceMatch&gt; faceMatches = match.getFaceMatches();<br> if (faceMatches != null) {<br> for (FaceMatch faceMatch: faceMatches){<br> Face face=faceMatch.getFace();<br> bandera=1;<br> }<br> }<br> }<br> } while (faceSearchResult !=null &amp;&amp; faceSearchResult.getNextToken() != null );</pre><pre>if(bandera==1){<br> notificacion.setVisibility(View.VISIBLE);<br> notificacion.setText(“ENCONTRADO”);<br> btnresultado.setVisibility(View.INVISIBLE);<br> }else<br> {<br> notificacion.setVisibility(View.VISIBLE);<br> notificacion.setText(“NO HAY COINCIDENCIAS”);<br> }<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*0sPEJVtQxlj9OVag" /></figure><p><strong>Sources</strong>:</p><p>[1]recovered from</p><p><a href="https://github.com/awslabs/aws-sdk-android-samples/tree/master/S3TransferUtilitySample">https://github.com/awslabs/aws-sdk-android-samples/tree/master/S3TransferUtilitySample</a></p><p>[2]recovered from</p><p><a href="https://github.com/googlesamples/android-vision/tree/master/visionSamples/barcode-reader">https://github.com/googlesamples/android-vision/tree/master/visionSamples/barcode-reader</a></p><p>[3]recovered from</p><p><a href="https://github.com/theappguruz/Android-Take-Photo-From-Camera-and-Gallery-Code-Sample">https://github.com/theappguruz/Android-Take-Photo-From-Camera-and-Gallery-Code-Sample</a></p><p>[4]recovered from</p><p><a href="https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html">https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html</a></p><p>[5]recovered from</p><p><a href="https://docs.aws.amazon.com/es_es/rekognition/latest/dg/create-collection-procedure.html">https://docs.aws.amazon.com/es_es/rekognition/latest/dg/create-collection-procedure.html</a></p><p>[6]recovered from</p><p><a href="https://docs.aws.amazon.com/es_es/rekognition/latest/dg/add-faces-to-collection-procedure.html">https://docs.aws.amazon.com/es_es/rekognition/latest/dg/add-faces-to-collection-procedure.html</a></p><p>[7]recovered from</p><p><a href="https://github.com/awslabs/aws-sdk-android-samples/blob/master/S3TransferUtilitySample/README.md">https://github.com/awslabs/aws-sdk-android-samples/blob/master/S3TransferUtilitySample/README.md</a></p><p><strong>Disclaimer</strong></p><p>At no time do I grant the authorship of this project as my own, recognizing that it is the adaptation / modification / union of several projects whose authors thank them for sharing their knowledge and whose links to their public repositories or websites are mentioned in sources.</p><p>The objective of this article is merely informative and with didactic purposes. Under no circumstances should it be considered for any purpose other than the one mentioned above.<br>The reference material is property of their respective owners and intellectual authors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d16f16d591c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/how-to-integrate-aws-rekognition-in-android/aws-rekognition-in-android-9d16f16d591c">AWS Rekognition in Android</a> was originally published in <a href="https://medium.com/how-to-integrate-aws-rekognition-in-android">How to integrate AWS Rekognition in Android</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>