【问题标题】:how to get state of same async class call multiple time in android?如何在android中多次获取相同异步类调用的状态?
【发布时间】:2015-05-02 12:35:11
【问题描述】:

我的要求是在循环中同时获取所有相同异步类调用的状态。

for (int i = 0; i < numberOfTasks; i++) {
        int taskId = i + 1;
        startTask(taskId, taskDuration, useParallelExecution);
    }

private void startTask(int taskId, int taskDuration, boolean useParallelExecution) {
    TestTask task = new TestTask(taskId, taskDuration);

    if (useParallelExecution) {
        // this type of executor uses the following params:
        //
        // private static final int CORE_POOL_SIZE = 5;
        // private static final int MAXIMUM_POOL_SIZE = 128;
        // private static final int KEEP_ALIVE = 1;
        //
        // private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        //     private final AtomicInteger mCount = new AtomicInteger(1);
        //
        //     public Thread newThread(Runnable r) {
        //         return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        //     }
        // };
        //
        // private static final BlockingQueue<Runnable> sPoolWorkQueue =
        //        new LinkedBlockingQueue<Runnable>(10);

        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } else {
        // this is the same as calling task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        task.execute();
    }
}

private class TestTask extends AsyncTask<Void, Void, Void> /* Params, Progress, Result */ {

    private final int id;
    private final int duration;

    TestTask(int id, int duration) {
        this.id       = id;
        this.duration = duration;
    }

    @Override
    protected Void doInBackground(Void... params) {
        int taskExecutionNumber = executedTasksCount.incrementAndGet();
        log("doInBackground: entered, taskExecutionNumber = " + taskExecutionNumber);
        SystemClock.sleep(duration); // emulates some job
        log("doInBackground: is about to finish, taskExecutionNumber = " + taskExecutionNumber);
        return null;
    }

    private void log(String msg) {
        Log.d("TestTask #" + id, msg);
    }
}

在这里,我必须同时获取所有 TestTask 异步类调用的状态。我对此做了很多研发,但没有得到任何解决方案。任何人都知道如何同时获取同一个异步类调用的状态然后帮助我。

提前谢谢你。

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    这里是解决方案。 首先,您必须将TestTask.class 的实例保存到某个列表中。为此使用HashMap&lt;Integer,TestTask&gt;,因为当您想通过 id 检查 asynctask 的状态时可能会更好。 现在您可以获得asyncTasks 的列表,因此只需创建for loop 并通过从您的循环位置计数中获取任务来检查状态。

    另一个提示,如果您想在 Activity 完成时检查状态,只需保存此 hashMap 并在需要检查任务状态时检索它。

    【讨论】:

    • 我还有一个问题是如果我的 5 个异步类正在运行,那么如何添加更多的两个异步类进行运行以及如何管理循环计数
    • 一次可以运行多少个 AsyncTask?在大多数 Android 版本中,答案是 128。为什么您通常会看到正好 5 个 AsyncTask 线程? AsyncTask 线程管理相当混乱,尤其是自从第一个 Android 版本以来它已经发生了很大变化。检查这个答案。stackoverflow.com/a/24506243/3728591
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多