微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

创建AsyncTask需要花费太多时间Android

我在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?或者有没有其他方法解决这个问题.(除了运行一个简单的线程?)
谢谢 :)

解决方法

如果你正在运行任何其他任务,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.

原文地址:https://www.jb51.cc/android/312984.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐