How to automatically start and stop an Async task in Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to automatically start and stop an Async task in Kotlin.

Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

<?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:id="@+id/relativeLayout"
   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:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:padding="8dp"
      android:text="Tutorials Point"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="48sp"
      android:textStyle="bold" />
   <ProgressBar
      android:id="@+id/progressBar"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:visibility="gone" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

Example

import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.ref.WeakReference
class MainActivity : AppCompatActivity() {
   var variable = 10
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      runTask()
   }
   private fun runTask() {
      val myToast = MyToast(this)
      myToast.execute(10)
   }
   companion object {
      class MyToast internal constructor(context: MainActivity) : AsyncTask<Int, String, String?>() {
         private var response: String? = null
         private val activityReference: WeakReference<MainActivity> = 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("Async Started..") // Calls onProgressUpdate()
         response = 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("Async Stopped..") // Calls onProgressUpdate()
            "Android was sleeping for " + params[0] + " seconds"
         } catch (e: InterruptedException) {
            e.printStackTrace()
            e.message
         } catch (e: Exception) {
               e.printStackTrace()
               e.message
            }
            return response
         }
         override fun onPostExecute(result: String?) {
            val activity = activityReference.get()
            if (activity == null || activity.isFinishing) return
            activity.progressBar.visibility = View.GONE
            activity.textView.text = result.let { it }
            activity.variable = 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()
         }
      }
   }
}

Step 4 − Add the following code to androidManifest.xml

Example

<xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q10">
   <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=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen


raja
Published on 23-May-2020 15:06:21
Advertisements