我正在运行AsyncTask,并在此线程中启动runOnUiThread来操纵我的视图。如果我关闭AsyncTask,则在关闭AsyncTask之后,runOnUiThread仍将运行1次。如何关闭runOnUiThread?谢谢!

@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);
}

最佳答案

我可以提出不同的解决方案吗?

在AsyncTask中实现onProgressUpdate(Params ...)方法。然后,您可以从doInBackground(Params ...)调用publishProgess;

onProgressUpdate(Params ...)将在ui线程上运行。

10-08 15:20