AsyncTask를 사용하여 시간이 많이 소요되는 작업을 실행하면 작업이 SD 카드를 스캔하고 유효한 모든 사진 절대 경로를 ArrayList 컨테이너에 추가합니다. 나는 AsyncTask에 연산을 넣어 실행한다. 시간이 걸리는 작업 Utils.getPhotoList();
은 doInbackgroud
방법 아래에 위치했습니다. 반환 값은 onPostExecute
메서드 아래의 전역 변수 list
에 할당되었습니다. 로그에서 메서드가 실행되었고 list
에 값이 할당되었음을 알았습니다. 하지만 방법 아래의 글로벌 변수 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를 시작한 후에 바로 목록 변수를 확인하기 때문에 null이거나 비어있을 수 있습니다. 이 체크를 AsyncTask의 onPostExecute 메소드에 넣고 거기에서 다른 프로세스를 시작해야합니다. 귀하의 AsyncTask가 다른 클래스에 있다면 당신의 활동은 호출자 클래스에 알리기 위해 인터페이스를 사용할 수 있습니다 –
@RajenRaiyarela 저, 저를 구 해주셔서 감사합니다! –