I have an AsyncTask reading from SharedPreferences. When I start the app the first time after installation, the AsyncTask takes a long time to call doInBackground()
method.
Here is the code:
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);
}
}
This is how I call the task:
new ReadSharedPrefsTask(getContext(), PREF_COUPON_IDS, this).execute();
And logcat prints:
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
As you can see, the time between finishing the Constructor and calling doInBackground is more than two minutes!
I tested it on Samsumng Galaxy S3 (4.2.2) and Nexus 4 (5.1) and this happens on both devices. But it does not happen on genymotion emulator.
Does anybody know this behaviour? What may cause it?
Did you execute any other asynctask before this one, started android API 11 AsyncTask are by default executed sequentially.
To run tasks independent of each other you must use the AsyncTask.THREAD_POOL_EXECUTOR. That requires a different executor:
// Go parallel!
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With