2014-09-02 173 views
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()); 
    } 
} 

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

+3

这是因为您在启动AsyncTask后立即检查列表变量,该变量在那里将为空或空。您需要将此检查放在AsyncTask的onPostExecute方法中,然后从那里启动任何其他进程。如果你的AsyncTask在另一个类然后你的活动,那么你可以使用接口来通知呼叫类 – 2014-09-02 10:48:44

+0

@RajenRaiyarela这节省了我,谢谢! – 2014-09-02 10:55:24

回答

0

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