0
我使用AsyncTask來執行耗時的操作,操作掃描SD卡並將所有有效的照片絕對路徑添加到ArrayList容器。我把操作放到AsyncTask中執行。耗時的操作Utils.getPhotoList();
被置於doInbackgroud
方法下。返回值按照onPostExecute
方法分配給全局變量list
。從日誌中,我知道該方法已執行,併爲list
分配了一個值。但爲什麼onStartCommand
方法下的全局變量list
始終是null
,這使我困惑不已。請參閱下面的代碼。android asynctask does not work
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());
}
}
任何反饋將不勝感激。謝謝!
這是因爲您在啓動AsyncTask後立即檢查列表變量,該變量在那裏將爲空或空。您需要將此檢查放在AsyncTask的onPostExecute方法中,然後從那裏啓動任何其他進程。如果你的AsyncTask在另一個類然後你的活動,那麼你可以使用接口來通知呼叫類 – 2014-09-02 10:48:44
@RajenRaiyarela這節省了我,謝謝! – 2014-09-02 10:55:24