繁体   English   中英

Android asynctask不起作用

[英]android asynctask doesnt work

我使用AsyncTask执行耗时的操作,该操作扫描SD卡并将所有有效的照片绝对路径添加到ArrayList容器。 我将操作放入AsyncTask中执行。 耗时的操作Utils.getPhotoList(); 被放置在doInbackgroud方法下。 返回值已在onPostExecute方法下分配给全局变量list 从日志中,我知道该方法已执行,并且为list分配了一个值。 但是为什么onStartCommand方法下的全局变量list始终为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());
   }
 }

任何反馈将不胜感激。 谢谢!

要解决该问题,只需将操作分成几部分即可。 将耗时的操作放在doInbackground()方法中,将结果放在onPostExecute()方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM