【问题标题】:Code structure with Asynctask AndroidAndroid Asynctask 的代码结构
【发布时间】:2013-05-08 16:27:31
【问题描述】:

我想我只是在制作“Spaghetti-Code”。也许一些专家可以帮助我为我的解决方案编写更好的代码。以下伪代码将显示我的问题:

我有一些运行时间很长的程序。此过程将显示一个进度条。我使用 Asynctasks 来实现这一点。这一切都很好,但我的代码不再可维护:

我希望留下简单的代码而不嵌套代码:

public void onCreate(Bundle savedInstanceState) {
LongrunningTask1();
dosomething1();
LongrunningTask2();
dosomething2();
LongrunningTask3();
dosomething3();
LongrunningTask4();
dosomething4(); 
}

我的异步任务代码:

    public void onCreate(Bundle savedInstanceState) {

    new LongrunningTask1().execute("Task1");

}
class LongrunningTask1 extends AsyncTask<String, Void, boolean> {
        private Exception exception;
        protected RSSFeed doInBackground(String... urls) {
            try {
                Do;
                return true;
            } catch (Exception e) {
                return null;
            }
        }
    protected void onProgressUpdate(Void... values) {
        updateprogressbar();
    }

        protected void onPostExecute(RSSFeed feed) {
        dosomething1();
        new LongrunningTask2().execute("Task2");
        }
     }
class LongrunningTask2 extends AsyncTask<String, Void, boolean> {
    similar to LongrunningTask1

        protected void onPostExecute(RSSFeed feed) {
        dosomething2();
        new LongrunningTask3().execute("Task3");
        }

}
class LongrunningTask3 extends AsyncTask<String, Void, boolean> {
    similar to LongrunningTask2

        protected void onPostExecute(RSSFeed feed) {
        dosomething3();
        new LongrunningTask4().execute("Task4");
        }
}
class LongrunningTask4 extends AsyncTask<String, Void, boolean> {
    similar to LongrunningTask3

        protected void onPostExecute(RSSFeed feed) {
        dosomething4();
        }
}

我想避免任何嵌套调用。谁能帮帮我?

问候

【问题讨论】:

    标签: java android coding-style android-asynctask


    【解决方案1】:

    为什么要在单独的线程中执行它们?您可以在一个 AsyncTask 中完成所有这些操作。

    也许您可以在ThreadPoolExecutor 上试一试?我用它来解决类似的问题。

    【讨论】:

    • 嗨。谢谢你的帮助。当然,在一个线程中执行所有东西会更容易,但是我不需要顺序地拥有线程。 ThreadPoolExecutor 很高兴知道其他情况。但就我而言,我真的很喜欢有一个简单的解决方案,如果有的话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2020-09-09
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多