1

I have an AsyncTask running and in this thread I start a runOnUiThread to manipulate my views. If I close my AsyncTask, the runOnUiThread runs still 1 time longer after I closed my AsyncTask. How can I close the runOnUiThread? Thanks!

@Override
protected String doInBackground(String... params) {
    while(running.get()) {

        // Background thread sleeps
        try {
            Thread.sleep(produceRadwaste_countdown * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // UI thread touching some view elements
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                radwasteTon.incrementStack();
            }
        });

        // Delete thread if player is game over
        if(GameLogic.isGameOver()) {
            clearThreads();
        }
    }

    return "Running";
}

public void clearThreads() {
    running.set(false);
    this.cancel(true);
}

1 Answers1

2

Can I propose different solution?

Implement onProgressUpdate(Params...) method in AsyncTask. Then you can call publishProgess from doInBackground(Params...);

onProgressUpdate(Params...) will be run on ui thread.

JoKr
  • 4,976
  • 8
  • 27
  • 39
  • Thanks it is working on the UI and I don't need the runOnUiThread, but it still runs 1 time after I canceled the thread –  Aug 29 '16 at 17:33
  • 1
    Okay I checked the whole process with logcat and it was a bit weird, because sometimes he executes publishProgress() before he checked the game over boolean and sometimes he checks the boolean before he executed publishProgress(). Now I am doing a little Thread.sleep between these both operations and it works, but I think this is not the best solution. –  Aug 29 '16 at 18:31
  • I read that AsyncTask has a max pool size and it would be a very bad thing for my game, because this thread will run on each game icon and I will have around 5 - 10 items. –  Sep 05 '16 at 08:58
  • Depending on the Android version, AsnycTask might have 5 or only 1 thread pool size. You can change tweak this using method `executeOnExector` and prodividing `Executor`. For more info you will need to search online, I haven't done this yet. Since I'm lazy, I would usually go for basic java Threads or RxJava in case like yours. – JoKr Sep 05 '16 at 16:07