ric*_*kul 3 multithreading android 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我称之为任务的方式:
new ReadSharedPrefsTask(getContext(), PREF_COUPON_IDS, this).execute();
Run Code Online (Sandbox Code Playgroud)
和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
Run Code Online (Sandbox Code Playgroud)
如您所见,完成构造函数和调用doInBackground之间的时间超过两分钟!
我在Samsumng Galaxy S3(4.2.2)和Nexus 4(5.1)上进行了测试,这种情况发生在两台设备上.但它不会发生在genymotion模拟器上.
有人知道这种行为吗?可能导致什么呢?
Gom*_*ino 23
你是否在此之前执行了任何其他asynctask,启动android API 11 AsyncTask默认按顺序执行.
要独立运行任务,必须使用AsyncTask.THREAD_POOL_EXECUTOR.这需要一个不同的执行者:
// Go parallel!
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2385 次 |
| 最近记录: |