我在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
实际上,在doInBackground方法中到达第一行几乎需要29秒,因为完成网络调用只花了36毫秒.我尝试了很多次,所用的时间几乎是一样的.
解决方法
如果你正在运行任何其他任务,AsyncTask正在等待其他AsyncTasks完成运行(检查你是否这样做).
见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.