2016-02-29 47 views
0

我需要從doInBackground()中調用task()函數AsyncTask類。任務函數包含2個子異步任務。所以task()立即從doInBackground()返回。在android中停止幷包裝2個子AsyncTask

  1. 是否有可能從其他地方停止(或標記此任務)此任務?
  2. 如何在一個包裝兩個子異步任務。
+1

你可以發佈你的代碼。 –

+0

明天我會發布我的代碼,因爲我離開我的電腦 – dearvivekkumar

回答

1

您不需要在doInBackground中調用另一個AsyncTask。事實上,一旦你達到了足夠高的API,你會得到一個異常。您可以在AsyncTask中調用另一個長時間運行的方法,而無需擔心線程;你已經在後臺線程中。如果您確實需要這些服務,請致電其他服務,但沒有理由這樣做。

要停止AsyncTask,只需重寫OnCancelled。然後,你可以致電:

task.cancel(true). 

編輯: 如果你想等待另一個進程完成,然後進行下一步,您可以等待該進程在你的類中設置一個全局變量完成或應用程序,然後進行線程睡眠,直到完成。

private boolean processIsDone = false. 

//then in your method you are calling from AsyncTask: 

private void myLongRunningMethod() { 
     //do your work here.... 

     //at the end set 
     processIsDone = true; 

} 

//in your AsyncTask: 
protected Void doInBackground(Void... params) { 
    //do first part of AsyncTask here 

    myLongRunningMethod(); 
    do { 
     try { 
      Thread.sleep(1500); 
     } catch (InterruptedException e) { 
       e.printStackTrace(); 
     } 
    } while (!processIsDone); 

    //finish the process here. 

    return null; 

} 
+0

如果funtion從doInBackground()立即返回,會發生什麼?我猜異步任務將立即完成...我想解決probkem5 – dearvivekkumar

+0

@dearvivekkumar - 不知道我明白 - 你是說你想等待任務完成? –

+0

是的。這正是我想要做的 – dearvivekkumar

0

我不明白這個問題究竟但也許這可以幫助:因爲你已經在後臺線程,而不是在主UI,你不會得到一個ANR。使用這個類在你的活動是這樣的:

myTask = new BackgroundAsyncTask().execute(); 
And cancel this way: 
myTask.cancel(true); 

這是類的代碼:

private class BackgroundAsyncTask extends AsyncTask<Object , Object ,String> { 

     protected void onPreExecute(){ 
      // Do Before execute the main task 
     } 

     protected String doInBackground(Object... param) { 
      //Execute the main task and return for example and String 
      return res; 
     } 

    protected void onPostExecute(String result) { 
     // You can use the String returned by the method doInBackground and  process it 
    } 

} 

希望這有助於

+0

我需要調用的函數是異步的,所以doInBackground立即返回。所以我想AsyncTask運行,直到我停止它從我的異步任務回調。 – dearvivekkumar

0

關於你的第一個問題,你可以在你的任務趕上事件被onCancelled()方法取消。嘗試這樣的:

private CancelTask extends AsyncTask { 

    private boolean cancelled = false; 
    protected void onCancelled() { 
     cancelled = true; 
    } 

    protected Object doInBackground(Object... obj) { 
     do { 
      // do something... 

     }while(!cancelled) 
    } 
} 

,並呼籲AsyncTask.cancel(true);當你想停下來。

CancelTask task = new CancelTask(); 
task.execute(); 
... 
task.cancel(true); 

關於第二個問題,我想知道如何處理兩個「Sub-AsyncTask」。

我會在更新代碼後嘗試尋找解決方案。