Enlace profundo en Android con ejemplo

Deep Linking es una de las características más importantes que utilizan varias aplicaciones para recopilar datos dentro de sus aplicaciones en forma de un enlace URL. Por lo tanto, se vuelve útil para los usuarios de otras aplicaciones compartir fácilmente los datos con diferentes aplicaciones. En este artículo, veremos la implementación de enlaces profundos en nuestra aplicación de Android. 

¿Qué es un enlace profundo? 

Un enlace profundo es un enlace URL que se genera, cuando alguien hace clic en ese enlace, nuestra aplicación se abrirá con una actividad específica o una pantalla. Usando esta URL podemos enviar un mensaje a nuestra aplicación con parámetros. En WhatsApp, podemos generar un enlace profundo para enviar un mensaje a un número de teléfono con algún mensaje. Los enlaces profundos se utilizan para abrir la pantalla específica de su aplicación con un enlace URL.   

¿Qué vamos a construir en este artículo? 

Construiremos una aplicación simple en la que crearemos un enlace profundo y al hacer clic en ese enlace pasaremos nuestro mensaje a nuestra aplicación y mostraremos ese mensaje en una vista de texto. qué

Implementación paso a paso

Paso 1: Crear un nuevo proyecto

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Tenga en cuenta que seleccione Java como lenguaje de programación.

Paso 2: trabajar con el archivo activity_main.xml

Vaya a la aplicación > res > diseño > actividad_principal.xml y agregue el siguiente código a ese archivo. A continuación se muestra el código para el archivo  activity_main.xml .

XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    tools:context=".MainActivity">
  
    <!--text view for displaying welcome message-->
    <TextView
        android:id="@+id/idTVWelcome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:text="Welcome to "
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/purple_500"
        android:textSize="30sp" />
  
    <!--text view for displaying the organization
        name from the link which we have generated-->
    <TextView
        android:id="@+id/idTVMessage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVWelcome"
        android:text="Organization Name"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/purple_500"
        android:textSize="30sp"
        android:textStyle="bold" />
      
</RelativeLayout>

Paso 3: trabajar con el archivo AndroidManifest.xml

Vaya a la aplicación > AndroidManifest.xml y agréguele el siguiente código. Como estamos creando un enlace profundo para nuestro archivo MainActivity.java , tenemos que agregar este código en la parte MainActivity. A continuación se muestra el código que se agregará en el archivo AndroidManifext.xml . Se agregan comentarios en el código para conocer con más detalle. 

XML

<!--as we want to open main activity from our link so we are specifying
    only in main activity or we can specify that in different activity as well
    on below line we are adding intent filter to our MainActivity-->
<intent-filter>
  <!--below line is to set the action to our intent to view-->
  <action android:name="android.intent.action.VIEW" />
    
  <!--on below line we are adding a default category to our intent-->
  <category android:name="android.intent.category.DEFAULT" />
    
  <!--on below line we are adding a category to make our app browsable-->
  <category android:name="android.intent.category.BROWSABLE" />
    
  <!--on below line we are specifying the host name and
      the scheme type from which we will be calling our app-->
   <data
        android:host="www.chaitanyamunje.com"
        android:scheme="https" />
</intent-filter>
  
<!--below is the same filter as above just the scheme is changed to http -->
<!--so we can open our app with the url starting with https and http as well-->
<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  
  <data
    android:host="www.chaitanyamunje.com"
    android:scheme="http" />
</intent-filter>

A continuación se muestra el código completo del archivo AndroidManifest.xml .

XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.deeplinks">
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.DeepLinks">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
  
            <!--as we want to open main activity from our link so we are specifying
                only in main activity or we can specify that in different activity as well-->
            <!--on below line we are adding intent filter to our MainActivity-->
            <intent-filter>
                <!--below line is to set the action to our intent to view-->
                <action android:name="android.intent.action.VIEW" />
                <!--on below line we are adding a default category to our intent-->
                <category android:name="android.intent.category.DEFAULT" />
                <!--on below line we are adding a category to make our app browsable-->
                <category android:name="android.intent.category.BROWSABLE" />
                <!--on below line we are specifying the host name and
                    the scheme type from which we will be calling our app-->
                <data
                    android:host="www.chaitanyamunje.com"
                    android:scheme="https" />
            </intent-filter>
  
            <!--below is the same filter as above just the scheme is changed to http -->
            <!--so we can open our app with the url starting with https and http as well-->
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
  
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
  
                <data
                    android:host="www.chaitanyamunje.com"
                    android:scheme="http" />
            </intent-filter>
  
        </activity>
    </application>
</manifest>

Paso 4: trabajar con el archivo MainActivity.java

Vaya al archivo MainActivity.java y consulte el siguiente código. A continuación se muestra el código del archivo MainActivity.java . Se agregan comentarios dentro del código para comprender el código con más detalle.

Java

package com.example.deeplinks;
  
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
  
import androidx.appcompat.app.AppCompatActivity;
  
import java.util.List;
  
public class MainActivity extends AppCompatActivity {
  
    // creating a variable for our text view
    private TextView messageTV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variable
        messageTV = findViewById(R.id.idTVMessage);
          
        // getting the data from our
        // intent in our uri.
        Uri uri = getIntent().getData();
          
        // checking if the uri is null or not.
        if (uri != null) {
            // if the uri is not null then we are getting the 
            // path segments and storing it in list.
            List<String> parameters = uri.getPathSegments();
              
            // after that we are extracting string from that parameters.
            String param = parameters.get(parameters.size() - 1);
              
            // on below line we are setting
            // that string to our text view
            // which we got as params.
            messageTV.setText(param);
        }
    }
}

Ahora hemos agregado la URL en nuestro archivo AndroidManifest como https://www.chaitanyamunje.com/hello/GeeksForGeeks . La URL desde la cual enviaremos mensajes a nuestro archivo MainActivity.java. En la URL anterior, «https» es nuestro esquema, «www.chaitanyamunje.com» es nuestro nombre de host y «hola» es nuestro primer parámetro y «GeeksForGeeks» es un segundo parámetro que mostraremos en nuestra aplicación como organización. nombre. Puede cambiar sus parámetros según sus requisitos. Ahora ejecute su aplicación y vea el resultado de la aplicación.

Producción:

A medida que haya ejecutado su aplicación, podrá ver el texto como Nombre de la organización, ahora cierre la aplicación y haga clic en el enlace que se muestra arriba desde el dispositivo en el que está instalada su aplicación. Después de hacer clic en ese enlace, se mostrará un mensaje emergente para seleccionar la aplicación. Dentro de ese mensaje emergente, seleccione su aplicación y su aplicación estará abierta. Estamos pasando un mensaje como «GeeksForGeeks» que se mostrará en el lugar del nombre de la Organización.

Publicación traducida automáticamente

Artículo escrito por chaitanyamunje y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *