2012-11-30 144 views
1

请帮忙。我可以重新启动AsyncTask。第二次调用updatePoi()时,应用程序每次崩溃。无法停止/重新启动AsyncTask

这里是我的代码:

  1. 我检查任务的状态,并配置取消(真)。

    public void updatePoi() { 
        //new RefreshMapTask().execute(); 
        if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING || 
         refreshMapTask.getStatus() == AsyncTask.Status.PENDING) { 
          refreshMapTask.cancel(true); 
         } 
         refreshMapTask.execute(); 
        } 
    } 
    
  2. 这是我的AsyncTask。在doInBackground,我写了一个休息时间。

    private class RefreshMapTask extends AsyncTask<Void, Void, Void> { 
        @Override 
        protected void onPreExecute() { 
         super.onPreExecute(); 
         getMapView().getOverlays().clear(); 
         myPoiOverlay.clear(); 
         exitOverlay.clear(); 
        } 
    
    
        @Override 
        protected Void doInBackground(Void... voids) { 
         Application app = (Application)getApplication(); 
         Log.d(TAG, "exits count = " + app.getExits().size()); 
    
         GeoPoint pointToNavigate = null; 
    
         for (Exit exit : app.getExits()) { 
    
          for (Poi poi : exit.getPoi()) { 
           if (isCancelled()){ 
            break; 
           } 
           //some code here 
          } 
         } 
    
         //small code here 
         return null; 
        } 
    
        @Override 
        protected void onPostExecute(Void aVoid) { 
         getMapView().invalidate(); 
        } 
    } 
    

编辑:从评论添加到解决问题

public void updatePoi() { 
//new RefreshMapTask().execute(); 
if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING || 
    refreshMapTask.getStatus() == AsyncTask.Status.PENDING){ 
    refreshMapTask.cancel(true); 
    refreshMapTask = new RefreshMapTask(); 
} else { 
    refreshMapTask = new RefreshMapTask(); 
} 
refreshMapTask.execute(); 
} 
+0

为什么你把doinbaground为无效,并返回为空 – appukrb

回答

7

AsyncTask实例只能调用一次。要进行第二次调用,您需要创建一个新实例。

+0

我知道,这就是为什么我试图杀死的AsyncTask,再次调用它。 –

+0

杀什么都不会做,它仍然是相同的实例。 – Shakti

+0

取消它,然后让它空,如果你不得不重新启动它,然后再指定值,然后再次拨打 –

0

尝试

return null; 

最终代码

@Override 
protected Void doInBackground(Void... voids) { 
    Application app = (Application)getApplication(); 
    Log.d(TAG, "exits count = " + app.getExits().size()); 

    GeoPoint pointToNavigate = null; 

    for (Exit exit : app.getExits()) { 

     for (Poi poi : exit.getPoi()) { 
      if (isCancelled()){ 
       return null; 
      } 
      //some code here 
     } 
    } 

    //small code here 
    return null; 
} 
+0

没有帮助:( –

2

你不能重启的任务。每个任务对象只能执行一次:

任务只能执行一次(如果第二试图执行一个将引发异常)

所以每次创建新的对象你执行它,不要使用同一个对象。