Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Without AsyncTask, running a thread in background and updating the UI Thread

I was trying to update the recycler view content from a background thread in Kotlin. I am not using AsyncTask.

Here is my code, i want to know if there is any better way than this:

In my MainActivity, i have progressThread as a member variable.

 var progressThread = Thread()

Then in my method where i want to run the thread first i am defining it...like

        progressThread = Thread (
    Runnable {
        kotlin.run {
            try {
            while (i <= 100 && !progressThread.isInterrupted) {
                Thread.sleep(200)
                //Some Logic
                runOnUiThread {
                    //this runs in ui thread

                }
                i++
            }
            }catch (e:InterruptedException){
                progressThread.interrupt()
            }
        }
    })

after that i am starting it in the same method as

 progressThread.start()

and for stopping it, i have a listener to cancel the progress and in the callback of that listener, i have written:

 progressThread.interrupt()
like image 977
Samrat Avatar asked Feb 06 '18 05:02

Samrat


People also ask

What are different ways of updating UI from background thread?

In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });

Which method is used to go back to UI thread from a background thread?

You can use runOnUiThread() method of activity to update UI from background thread. Or you can use a android Handler to achieve this.

Why should you avoid to run non UI code on the main thread?

If you put long running work on the UI thread, you can get ANR errors. If you have multiple threads and put long running work on the non-UI threads, those non-UI threads can't inform the user of what is happening.

Is it possible to start AsyncTask from background thread?

Android App Development for Beginners Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.


1 Answers

Updated

Coroutines are stable now,: https://kotlinlang.org/docs/reference/coroutines-overview.html


Old Answer

Yes, you can do this using doAsync from kotlin anko library that is fairly simple and easy to use.

add following line in module level gradle file:

compile "org.jetbrains.anko:anko-commons:0.10.0"

Code example:

val future = doAsync {
    // do your background thread task
    result = someTask()

    uiThread {
        // use result here if you want to update ui
        updateUI(result)
    }
}

code block written in uiThread will only be executed if your Activity or Fragment is in foreground mode (It is lifecycle aware). So if you are trying to stop thread because you don't want your ui code to execute when Activity is in background, then this is an ideal case for you.

As you can check doAsync returns a Future object so you can cancel the background task, by cancel() function:

future.cancel(true)

pass true if you want to stop the thread even when it has started executing.

If you have more specialised case to handle stopping case then you can do the same thing as in your example.

You can use Kotlin Coroutines also but its in Experimental phase, still you can try it out: https://kotlinlang.org/docs/reference/coroutines.html

like image 173
chandil03 Avatar answered Sep 28 '22 14:09

chandil03