2017-02-28 272 views
0

我在這個主題上做了大量的閱讀,但沒有找到正確的解決方案。取消AsyncTask的問題

我有一個程序,它執行網絡發現(使用ping)。我不明白你如何停止異步任務。我正在做一個任務。(真)但它似乎什麼都不做。最重要的是,我正在做一段時間()來檢查任務是否被取消,並立即返回true。

序列:是開始(正常工作)我等5-10個IP地址,我點擊按鈕停止。然後我點擊開始,但發現任務沒有執行。

我們真的可以停止異步任務嗎?怎麼樣?它的延遲是什麼?

編輯

我迷路了。 Stackoverflow中的所有Q都聲明取消(true)需要來自任務。

  1. 我有一個例子,我叫取消(真)doinbackground內,但它並沒有引發onCancelled

  2. 大多數情況下(至少循環)停得來的外任務。我下面的例子只是在循環計數器上播放。這樣可行。

一個interisting評論從wrygiel在Q Ideal way to cancel an executing AsyncTask

來到這將是巨大的,有一個真實的例子。

這裏是我的代碼修改,但onCancelled沒有工作,所以我玩循環計數器。

public class MainActivity extends AppCompatActivity { 
    TextView text; 
    Discover discover; 
    int count; 
    private boolean running = true; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Button start = (Button) findViewById(R.id.start); 
     Button stop = (Button) findViewById(R.id.stop); 
     text = (TextView) findViewById(R.id.txt); 

     start.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       discover = new Discover(); 
       discover.execute(); 
      } 
     }); 

     stop.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
     //  if(discover != null) 
     //   discover.cancel(true); 
       count = 255; 
      } 
     }); 
    } 

    private class Discover extends AsyncTask<Object, String, Void> { 

     @Override 
     protected Void doInBackground(Object... params) { 
      String ip; 
      Ping ping = new Ping(); 

      for(count=1;count<255;count++) { 
       if(!running) { 
        count = 255; 
        Log.i("Discover", "task terminated"); 
       } 
       ip = "192.168.1." + count; 
       if (!ping.pong(ip)) 
        publishProgress(ip+" not alive "); 
       else 
        publishProgress(ip+" is alive"); 
      } 
      return null; 
     } 

     @Override 
     protected void onPreExecute() { 
      text.setText("Start search..."); 
      super.onPreExecute(); 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
      super.onProgressUpdate(values); 
      text.setText(values[0]); 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      text.setText("Task finished"); 
      super.onPostExecute(result); 
     } 

     @Override 
     protected void onCancelled() { 
      running = false; 
      super.onCancelled(); 
     } 

    } 
} 
+2

檢查http://stackoverflow.com/a/2740204/4854450 –

回答

1

你不能停止的AsyncTask這種方式。您可以隨時使用discover.cancel(true);,但必須手動停止它 - 在doInBackground方法中檢查值discover.isCancelled()。否則AsyncTask將調用整個doInBackground方法,但不會經過onPostExecute

具有內置 onCancelled()方法
0

的AsyncTask像onPostExecute()

@Override 
    protected void onCancelled() { 
     super.onCancelled(); 
    } 

,你需要定期檢查的AsyncTask的狀態,在後臺的功能,當你取消它,onCancelled()方法將調用,而不是onPostExecute()