gpt4 book ai didi

android - 创建 AsyncTask 花费太多时间 Android

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:12:40 25 4
gpt4 key购买 nike

我正在 AsyncTask 中进行网络调用,但我面临的问题是启动 doInBackground 方法所花费的时间。

这是我的部分代码:

    button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Temp:",System.currentTimeMillis()+"");
new Move().execute();
/*some other logic
}
}

我的 AsyncTask 是:

    private class Move extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... temp) {
Log.d("start:",System.currentTimeMillis()+"");
gson.fromJson(Web.Request.get(some_URL),Void.class);
Log.d("end:",System.currentTimeMillis()+"");
return null;
}
}

这些是我得到的日志:

           32658-998/com.example.game D/temp:﹕ 1408923006159
32658-998/com.example.game D/start:﹕ 1408923035163
32658-998/com.example.game D/end:﹕ 1408923035199

所以实际上它花了将近 29 秒才到达 doInBackground 方法的第一行,而完成网络调用只用了 36 毫秒。试了很多次,用的时间几乎是同一个顺序。

是否可以立即启动 AsyncTask?或者有没有其他方法可以解决这个问题。(除了运行一个简单的线程之外?)谢谢:)

最佳答案

AsyncTask 正在等待其他 AsyncTask 完成运行,如果您有任何其他任务正在运行(检查是否有),大概是这样。

参见 here .

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

关于android - 创建 AsyncTask 花费太多时间 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com