Blog purpose for android basic example for android app developer. any query please my contact

Thursday, 18 February 2021

kotlin asynctask example

 kotlin asynctask example

In this Article Today Learn kotlin asynctask example. Async Process also Background Process Like Download File or Other Process in Android App. Follow the kotlin asynctask example.


1.Asynct.kt:

package com.akash.kotlinlistview.AsyncTask

import android.app.Activity

import android.os.Bundle

import kotlinx.android.synthetic.main.activity_main.*

import android.os.AsyncTask

import android.view.View

import android.widget.Toast

import com.akash.kotlinlistview.R

import kotlinx.android.synthetic.main.activity_asynct.*

import java.lang.ref.WeakReference


class Asynct : Activity() {

    var myVariable = 10


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_asynct)


        btnDoAsync.setOnClickListener {

            val task = MyAsyncTask(this)

            task.execute(10)

        }

    }

    companion object {

        class MyAsyncTask internal constructor(context: Asynct) : AsyncTask<Int, String, String?>() {

            private var resp: String? = null

            private val activityReference: WeakReference<Asynct> = WeakReference(context)


            override fun onPreExecute() {

                val activity = activityReference.get()

                if (activity == null || activity.isFinishing) return

                activity.progressBar.visibility = View.VISIBLE

            }

            override fun doInBackground(vararg params: Int?): String? {

                publishProgress("Sleeping Started") // Calls onProgressUpdate()

                try {

                    val time = params[0]?.times(1000)

                    time?.toLong()?.let { Thread.sleep(it / 2) }

                    publishProgress("Half Time") // Calls onProgressUpdate()

                    time?.toLong()?.let { Thread.sleep(it / 2) }

                    publishProgress("Sleeping Over") // Calls onProgressUpdate()

                    resp = "Android was sleeping for " + params[0] + " seconds"

                } catch (e: InterruptedException) {

                    e.printStackTrace()

                    resp = e.message

                } catch (e: Exception) {

                    e.printStackTrace()

                    resp = e.message

                }


                return resp

            }


            override fun onPostExecute(result: String?) {


                // execution of result of Long time consuming operation

                val activity = activityReference.get()

                if (activity == null || activity.isFinishing) return

                // access Activity member variables or modify the activity's UI

                activity.progressBar.visibility = View.GONE

                activity.textView.text = result.let { it }

                activity.myVariable = 100

            }


            override fun onProgressUpdate(vararg text: String?) {


                val activity = activityReference.get()

                if (activity == null || activity.isFinishing) return


                Toast.makeText(activity, text.firstOrNull(), Toast.LENGTH_SHORT).show()


            }

        }

    }

}



2.activity_asynct.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="@color/colorAccent"
    tools:context=".Asynct ">


    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnDoAsync"
        android:gravity="center"
        android:text=" Async Task " />

    <Button
        android:id="@+id/btnDoAsync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:text="Click ASYNC TASK" />


    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnDoAsync"
        android:visibility="gone"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

3.AndroidManifest.xml:

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

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

    <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/AppTheme">
        <activity android:name=".AsyncTask.Asynct">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

4.styles.xml:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

5.colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
</resources>

6.strings.xml:

<resources>
    <string name="app_name">Async Task</string>
</resources>

7.Output:

kotlin asynctask example



kotlin asynctask example






No comments:

Post a Comment