AsyncTask en Kotlin

Uso de AsyncTask en Kotlin

Hilos y procesos en Android

4.- Tareas en segundo plano con AsyncTask

Ejemplo: AsyncTask en Android

Ejercicio: Descargar un fichero de Internet

Creación de un nuevo proyecto en Android Studio: ConexionAsincronaKotlin

– Dar permisos en el manifiesto

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.ConexionAsincronaKotlin"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

– Usar view binding

build.gradle:

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.example.conexionasincronakotlin"
    compileSdk = 34

    buildFeatures {
        viewBinding = true
    }

strings.xml

<resources>
    <string name="app_name">Conexion Asíncrona en Kotlin</string>
    <string name="web">https://dam.org.es/ficheros/frases.html</string>
    <string name="descargar">Descargar</string>
</resources>

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:id="@+id/myLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="@string/web"
        android:textAppearance="@android:style/TextAppearance.Material.Large"
        app:layout_constraintBottom_toTopOf="@+id/switch1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="OkHttp"
        android:textAlignment="textEnd"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        android:text="@string/descargar"
        app:layout_constraintBottom_toTopOf="@+id/webView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch1" />

    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="79dp"
        android:text="Tiempo de descarga"
        android:textAppearance="@android:style/TextAppearance.Material.Large"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/webView" />
</androidx.constraintlayout.widget.ConstraintLayout>

– Descargar un fichero usando Java.net

Clase Result

class Result {
    var code = 0 //indica el código de estado devuelto por el servidor web
    lateinit var message: String //información del error
    lateinit var content: String //fichero descargado
}

Objeto Connection

object Connection {

    @Throws(IOException::class)
    fun connectJava(url: URL?): Result {







    }

MainActivity.kt

class MainActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var binding: ActivityMainBinding
    var start: Long = 0
    var end: Long = 0
    lateinit var myAsyncTask: MyAsyncTask
    lateinit var url: URL

    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.button.setOnClickListener(this)
    }

    override fun onClick(view: View) {
        try {
            url = URL(binding.editText.text.toString())
            if (binding.switch1.isChecked) {
                //descarga usando OkHttp
                OkHTTPdownload(url)
            } else  // descarga usando AsyncTask y Java.net
                download(url)
        } catch (e: MalformedURLException) {
            e.printStackTrace()
            showError(e.message)
        } catch (ex: IOException) {
            showError(ex.message)
        }
    }

    private fun OkHTTPdownload(web: URL) {
        





    }

    private fun download(url: URL) {
        start = System.currentTimeMillis()
        myAsyncTask = MyAsyncTask(this)
        myAsyncTask.execute(url)
        binding.textView.text = "Descargando la página"
    }

    private fun showError(mensaje: String?) {
        Toast.makeText(this, mensaje, Toast.LENGTH_SHORT).show()
    }

    inner class MyAsyncTask(private val context: Context) : AsyncTask<URL?, Void?, Result>() {













    }
}

Creación de la tarea asíncrona usando AsyncTask (en MainActivity)

inner class MyAsyncTask(private val context: Context) : AsyncTask<URL?, Void?, Result>() {
    private lateinit var progress: ProgressDialog

    override fun onPreExecute() {
 



    }

    protected override fun doInBackground(vararg url: URL?): Result {







    }

    override fun onPostExecute(result: Result) {




    }

    override fun onCancelled() {


    }
}

– Error: Cleartext http not permitted:

usesCleartextTraffic

cleartext http traffic not permitted

– Prueba:

Acceso a un servidor web en la red local

Acceso a un servidor web en Internet: https://dam.org.es/ficheros/frases.html

Errores: página no encontrada, servidor caído, etc

Deja una respuesta