Intents en Kotlin

Qué es un intent?

Intents and filters

Los intents: tipos y ejemplos (punto 7 de la unidad 2)

Intents y filtros de intents

Ejemplo de intent implícito

// Create the text message with a string
val sendIntent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, textMessage)
    type = "text/plain"
}

// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(packageManager) != null) {
    startActivity(sendIntent)
}

Forzar un selector de apps:

val sendIntent = Intent(Intent.ACTION_SEND)
...

// Always use string resources for UI text.
// This says something like "Share this photo with"
val title: String = resources.getString(R.string.chooser_title)
// Create intent to show the chooser dialog
val chooser: Intent = Intent.createChooser(sendIntent, title)

// Verify the original intent will resolve to at least one activity
if (sendIntent.resolveActivity(packageManager) != null) {
    startActivity(chooser)
}

Intents comunes

Ejemplo: Navegador web

intent.resolveActivity returns null in API 30

Package visibility in Android 11

Ejemplo: Intents implíctos y explícitos

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/intents"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.046" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:text="Navegador"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.005" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="Mapa"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="Teléfono"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Pepe"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Saludar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="Respuesta"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button4" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="@string/nombre"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="92dp"
        android:text="@string/volver"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.002" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="@string/adios"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

build.gradle

buildFeatures {
    viewBinding = true
}

MainActivity.kt

package com.example.intentskotlin

import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.content.Intent.CATEGORY_BROWSABLE
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.example.intentskotlin.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var binding: ActivityMainBinding
    private lateinit var launcher: ActivityResultLauncher<Intent>
    var code = 1

    companion object {
        const val RESULTADO = "resultado"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view: View = binding.root
        setContentView(view)

        binding.button1.setOnClickListener(this)
        binding.button2.setOnClickListener(this)
        binding.button3.setOnClickListener(this)
        binding.button4.setOnClickListener(this)
        binding.button5.setOnClickListener(this)

        launcher = registerForActivityResult<Intent, ActivityResult>(
            ActivityResultContracts.StartActivityForResult()
        ) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                binding.editText.setText("Respuesta: " + data!!.getStringExtra(RESULTADO))
            }
        }
    }

    override fun onClick(view: View) {
        lateinit var intent: Intent

        if (view === binding.button1) {
            //ACTION_VIEW. Abrir el navegador con una URL indicada como dato
            val link = "https://kotlin.org"

            openWebPage(link)
        }
        if (view === binding.button2) {
            //ACTION_VIEW. Muestra dirección en mapa indicada como dato
            // (El emulador o AVD en el que se pruebe debe incluir las API de Google)
            val dir = "Calle+Larios+Malaga"
            showMap(Uri.parse("geo:0,0?q=$dir"))
        }
        if (view === binding.button3) {
            // ACTION_DIAL.Marca el número de teléfono indicado como dato.
            val phoneNumber: String = "951297929"

            call(phoneNumber)
        }
        if (view === binding.button4) {
            intent = Intent(this, SecondActivity::class.java)
            val extras = Bundle()
            extras.putString("usuario", binding.editText.text.toString())
            extras.putInt("edad", 27)
            intent.putExtras(extras)
            startActivity(intent)
        }
        if (view === binding.button5) {
            intent = Intent(this, SecondActivity::class.java)
            val extras = Bundle()
            extras.putString("usuario", binding.editText.text.toString())
            extras.putInt("edad", 27)
            intent.putExtras(extras)
            // startActivityForResult(intent, code)
            launcher.launch(intent)
        }
    }

    fun openWebPage(url: String) {

        val webPage: Uri = Uri.parse(url)
        /*
        val intent = Intent(Intent.ACTION_VIEW, webpage)

        if (intent.resolveActivity(packageManager) != null) {
            startActivity(intent)
        } else {
            Toast.makeText(this, "Error al lanzar el intent del navegador", Toast.LENGTH_SHORT).show()
        }
        */
        try {
            val browserIntent = Intent()
                .setAction(ACTION_VIEW)
                .addCategory(CATEGORY_BROWSABLE)
                .setData(webPage)
            startActivity(browserIntent)
        } catch (e: ActivityNotFoundException) {
            Toast.makeText(this,"Error al lanzar el intent del navegador " + e.message.toString(),Toast.LENGTH_SHORT)
                .show()
            Log.e("Error", e.message.toString())
        }
    }

    fun showMap(geoLocation: Uri) {
        try {
            val intent = Intent()
                .setAction(Intent.ACTION_VIEW)
                .setData(geoLocation)
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            Toast.makeText(this, "Error al lanzar el intent del mapa " + e.message.toString(), Toast.LENGTH_SHORT)
                .show()
            Log.e("Error", e.message.toString())
        }
    }

    fun call(phoneNumber: String) {
        val dialIntent = Intent(Intent.ACTION_DIAL)
        dialIntent.data = Uri.parse("tel:$phoneNumber")

        if (intent.resolveActivity(packageManager) != null) {
            startActivity(dialIntent)
        } else {
            Toast.makeText(this, "Error al lanzar el intent del teléfono", Toast.LENGTH_SHORT)
                .show()
        }
    }
    /*
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)

            if (requestCode == code && resultCode == RESULT_OK) {
                val res = data!!.extras!!.getString(RESULTADO)

                binding.editText.setText("Respuesta: " + res)
            }
        }
     */
}

SecondActivity.kt

package com.example.intentskotlin

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.intentskotlin.databinding.ActivitySecondBinding

class SecondActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var binding: ActivitySecondBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivitySecondBinding.inflate(layoutInflater)
        val view: View = binding.root
        setContentView(view)

        binding.button.setOnClickListener(this)
        val extras = intent.extras
        //recupera el valor asociado a “usuario”
        val str = extras!!.getString("usuario")
        //recupera el valor asociado a “edad”
        val edad = extras!!.getInt("edad")
        binding.textView.text = "Hola: $str, $edad"
    }

    override fun onClick(view: View) {
        if (view === binding.button) {
            val intent = Intent()
            intent.putExtra(MainActivity.RESULTADO, binding.editText.text.toString())
            setResult(RESULT_OK, intent)
            finish()
        }
    }
}

 

 

Ejercicio 2 de la tarea online

Más información:

Comunicar actividades a través de Intents

Deja una respuesta