AsyncTask 需要很长时间才能进入 doInBackground()

AsyncTask takes a long time before entering doInBackground()

我有一个从 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模拟器上。

有人知道这种行为吗?可能是什么原因造成的?

也许您正在实例化一个新任务,稍后调用execute()。也就是说,如果您要调用:

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

尝试将调用链接起来:

new ReadSharedPrefsTask().execute();

在启动这个之前,您是否执行过任何其他异步任务 android API 11 个 AsyncTask 默认按顺序执行。

要运行任务相互独立你必须使用AsyncTask.THREAD_POOL_EXECUTOR。这需要不同的执行者:

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