gizmoGremlin
7/5/2019 - 2:06 PM

manually create Threads- Kotlin Reference

manually create Threads- Kotlin Reference

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button

class MainActivity : AppCompatActivity() {

    lateinit var startButton :Button
  //  lateinit var mainHandler : Handler
    var terminateThread: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    //    mainHandler = Handler()
        startButton = findViewById(R.id.btn_start)

        startButton.setOnClickListener {
            startThread(it as Button)
        }

        val stopButton = findViewById<Button>(R.id.btn_stop)

        stopButton.setOnClickListener {
            stopThread()
        }



    }


    fun startThread(btn : Button){
       /* val thread = ExampleThread(10)
        thread.start()*/
        terminateThread = false
        val runnable = ExampleRunnable(10, btn)
        Thread(runnable).start()

    }
    fun stopThread(){
        terminateThread = true
    }


    class ExampleThread(var seconds: Int) : Thread() {


        @Override
        override fun run() {

            for (i in 0 until seconds){
                Log.d(TAG, "start Thread: $i")
                Thread.sleep(1000)

            }

        }

    }
   inner class ExampleRunnable(var seconds: Int, var btn: Button): Runnable{
        override fun run() {

            for (i in 0 until seconds){

                if (terminateThread == true){
                    return
                }
                Log.d(TAG,"$i")
                if (i == 5){
                    /*val threadHandler = Handler(Looper.getMainLooper())

                    threadHandler.post( object : Runnable{
                        override fun run() {
                            btn.text = i.toString()
                        }

                    })
*/                 /* Log.d(TAG,"Inside")
                    btn.post( object: Runnable{
                        override fun run() {
                            btn.text = i.toString()
                        }

                    } )*/
                    runOnUiThread( object :Runnable{
                        override fun run() {
                            btn.text = i.toString()
                        }

                    })
                }
                Thread.sleep(500)


            }


        }

    }



    companion object {
        const val TAG =  "MainActivity"
    }

}