

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to automatically start and stop an Async task in Kotlin?
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
- Related Questions & Answers
- How to execute an Async task repeatedly after fixed time intervals in Android using Kotlin?
- How to start the specific task of the task scheduler using PowerShell?
- Start and stop an Android notification from broadcast receiver?
- How to execute Async task repeatedly after fixed time intervals in Android?
- Different ways to start a Task in C#
- How to stop asynctask thread in Kotlin?
- Start and stop HANA system in SAP HANA Studio
- Stop and start a tenant database in SAP HANA
- Stop and start a particular database service in SAP HANA
- How to start Service using Alarmmanager in Kotlin Android?
- System privilege to start/stop a SAP HANA system
- How to catch an exception thrown by an async void method in C#?
- Promises Callbacks And Async/Await
- Async and Await in Dart Programming
- How to stop an infinite loop safely in Python?
Advertisements