我使用AsyncTask执行耗时的操作,操作扫描SD卡并将所有有效的照片绝对路径添加到ArrayList容器。我把操作放到AsyncTask中执行。耗时的操作Utils.getPhotoList();
置于doInbackgroud
方法下。返回值已分配给list
方法下的全局变量onPostExecute
。从日志中,我知道方法已执行,并为list
分配了一个值。但是为什么list
方法下的全局变量onStartCommand
总是null
,这让我很困惑。请参阅下面的代码。
ConcurrentAsyncTask.execute(new PhotoTask());
,完整的代码是
public int onStartCommand(Intent intent, int flags, int startId) {
if (isCameraUpload) {
// execute time-consuming operation
ConcurrentAsyncTask.execute(new PhotoTask());
}
// list is always null
if (list != null) {
notifyUser(photosCount, repoName);
}
return START_STICKY;
}
和自定义类ConcurrentAsyncTask是。
public class ConcurrentAsyncTask {
public static <T> void execute(AsyncTask<T, ?, ?> task, T...args) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) {
task.execute(args);
} else {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);
}
}
public static void execute(Runnable runnable) {
execute(new SimpleAsyncTask(runnable));
}
private static class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
Runnable runnable;
public SimpleAsyncTask(Runnable runnable) {
this.runnable = runnable;
}
public Void doInBackground(Void... args) {
try {
runnable.run();
} catch(Exception e) {
// ignore
}
return null;
}
}
并且PhotoTask
类是
private class PhotoTask extends AsyncTask<Void, Void, List<SelectableFile>> {
@Override
protected List<SelectableFile> doInBackground(Void... params) {
Log.d(DEBUG_TAG, "doInBackgroud");
Log.d(DEBUG_TAG, "doInBackgroud:pathList.size: " + Utils.getPhotoList().size());
return Utils.getPhotoList();
}
@Override
protected void onPostExecute(List<SelectableFile> result) {
Log.d(DEBUG_TAG, "onPostExecute");
list = result;
Log.d(DEBUG_TAG, "onPostExecute: list.size: " + list.size());
}
}
任何反馈意见将不胜感激。谢谢!
答案 0 :(得分:0)
解决问题,只需将操作分成几部分。将耗时的操作置于doInbackground()方法中,并将结果放在onPostExecute()方法中。