在进入doInBackground()之前,AsyncTask需要很长时间

时间:2015-06-03 11:18:13

标签: android multithreading android-asynctask

我从SharedPreferences读取了AsyncTask。当我在安装后第一次启动应用程序时,AsyncTask需要很长时间才能调用doInBackground()方法。

以下是代码:

public class ReadSharedPrefsTask extends AsyncTask{

    private static final String TAG = ReadSharedPrefsTask.class.getSimpleName();
    Context context;
    String key;
    Object result;
    OnReadFinishedListener listener;
    long startTime;

    /**
     * @param context the context
     * @param key the shared preferences key
     * @param listener a listener which gets informed when the read operation is finished
     */
    public ReadSharedPrefsTask(Context context, String key, OnReadFinishedListener listener){
        Log.d(TAG, "Ctor begin");
        startTime = System.currentTimeMillis();
        this.context = context.getApplicationContext();
        this.key = key;
        this.listener = listener;
        Log.d(TAG, "Ctor end; elapsed time: " + (System.currentTimeMillis() - startTime));

    }

    @Override
    protected Object doInBackground(Object[] params) {

        Log.d(TAG, "doInBackground; elapsed time: " + (System.currentTimeMillis() - startTime));

        SharedPreferences prefs = MASharedPreferences.get(context);

        Log.d(TAG, "doInBackground; elapsed time: " + (System.currentTimeMillis() - startTime));

        result = prefs.getAll().get(key);

        Log.d(TAG, "doInBackground; elapsed time: " + (System.currentTimeMillis() - startTime));

        return result;
    }

    @Override
    protected void onPostExecute(Object o) {

        Log.d(TAG, "onPostExecute; elapsed time: " + (System.currentTimeMillis() - startTime));
        super.onPostExecute(o);
        listener.onReadFinished(o, key);
    }

}

这就是我称之为任务的方式:

new ReadSharedPrefsTask(getContext(), PREF_COUPON_IDS, this).execute();

并且logcat打印:

D/ReadSharedPrefsTask﹕ Ctor begin
D/ReadSharedPrefsTask﹕ Ctor end; elapsed time: 3
D/ReadSharedPrefsTask﹕ doInBackground; elapsed time: 126478
D/ReadSharedPrefsTask﹕ doInBackground; elapsed time: 126480
D/ReadSharedPrefsTask﹕ doInBackground; elapsed time: 126481
D/ReadSharedPrefsTask﹕ onPostExecute; elapsed time: 126481

如您所见,完成构造函数和调用doInBackground之间的时间超过两分钟!

我在Samsumng Galaxy S3(4.2.2)和Nexus 4(5.1)上进行了测试,这种情况发生在两台设备上。但它不会发生在genymotion模拟器上。

有人知道这种行为吗?可能导致什么呢?

2 个答案:

答案 0 :(得分:22)

在此之前是否执行过任何其他asynctask,默认情况下启动android API 11 AsyncTask是按顺序执行的。

要独立运行任务,必须使用AsyncTask.THREAD_POOL_EXECUTOR。这需要一个不同的执行者:

   // Go parallel!
   task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

答案 1 :(得分:0)

也许你正在实例化一个新任务,以后调用execute()。也就是说,如果你打电话:

ReadSharedPrefsTask task = new ReadSharedPrefsTask();
//maybe some other code here?
task.execute();

尝试使用以下链接来跟踪:

new ReadSharedPrefsTask().execute();