Overview

Default execution takes place on the main application thread which is responsible for the UI. If the thread becomes blocked the application will become unresponsive. If an app is unresposive for too long an ANR, Android not responding messaging is generate. To avoid this we should run IO and blocking code on a background thread.

All events are collected in a queue and processed by the Looper class.

 class LooperHandler : Handler() { 
      override fun handleMessage(message: Message) { 
            ... 
      } 
    } 

    class LooperThread : Thread() { 
      var handler: Handler? = null 

      override fun run() { 
         Looper.prepare() 
         handler = LooperHandler() 
         Looper.loop() 
      } 
    }

Threads

ThreadPools and Executor classes are available to create background threads. Unlike AsyncTask, Executors can be run in parallel.

Delay Execution

class ItemsFragment : BaseFragment() { 
      ... 
      override fun onResume() { 
        super.onResume() 
        ... 
        val items = view?.findViewById<ListView>(R.id.items) 
        items?.let { 
            Handler().postDelayed({ 
                if (!activity.isFinishing) { 
                    items.setBackgroundColor(R.color.grey_text_middle) 
                } 
            }, 3000) 
         } 
        } 
       } 
       ...
     }

results matching ""

    No results matching ""