START AND STOP BUTTON
Sun Nov 03 2024 14:13:08 GMT+0000 (Coordinated Universal Time)
Saved by @sem
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.Toast import com.google.android.material.snackbar.Snackbar class MainActivity : AppCompatActivity() { private lateinit var startBtn : Button private lateinit var stopBtn : Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var task = LongOperation() startBtn = findViewById(R.id.start) stopBtn = findViewById(R.id.end) startBtn.setOnClickListener { val contextView = findViewById<View>(R.id.root) val snack = Snackbar.make(contextView, "Demonstration of Asynchronous Task", Snackbar.LENGTH_SHORT) snack.show() task.execute() } stopBtn.setOnClickListener { task.cancel(true) val contextView = findViewById<View>(R.id.root) val snack = Snackbar.make(contextView, "Asynchronous Task Interrupted", Snackbar.LENGTH_SHORT) snack.show() } } } Long Operation: import android.content.Context import android.os.AsyncTask import android.util.Log import android.widget.Toast import androidx.core.content.ContextCompat import kotlin.coroutines.coroutineContext class LongOperation : AsyncTask<String?, Void?, String>() { protected override fun doInBackground(vararg params: String?): String? { try { Thread.sleep(100000) } catch (e: InterruptedException) { Log.e("LongOperation", "Interrupted", e) return "Interrupted" } return "Executed" } override fun onPostExecute(result: String) {} companion object { fun execute() {} } } Activity.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/root" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.google.android.material.button.MaterialButton android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="54dp" android:layout_margin="8dp" android:text="Start Task" app:layout_constraintBottom_toTopOf="@+id/end" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_chainStyle="packed" /> <com.google.android.material.button.MaterialButton android:id="@+id/end" android:layout_width="wrap_content" android:layout_height="54dp" android:layout_margin="8dp" android:text=" End Task " app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/start" /> </androidx.constraintlayout.widget.ConstraintLayout>
Comments