-2

當我的應用程序啓動時,用戶會看到包含圖像的ListView。正在使用AsyncTask下載這些圖像。如果您多次打開該片段 - 圖片會持續加載很長一段時間的項目。如何在片段啓動時停止正在運行的線程?

據我所知,這是因爲許多下載AsyncTasks正在創建,並且許多重複的圖像正在下載,因爲ListView已被連續調用幾次。

我的問題是如何在碎片啓動時完成停止這些正在運行的線程?

回答

0

而不是再次打開片段時停止它們,只要片段被破壞就停止它們。

@Override 
public void onDestroy(){ 
    super.onDestroy(); 
    task.cancel(); 
} 
0

線程的stop(),suspend()等,方法已被棄用,安全終止線程的唯一方法是讓它退出它的run()方法,也許通過未經檢查的異常。


的方法提出有使用揮發性停止標誌(方向指示燈在下面的代碼)

private volatile Thread blinker; 
public void stop() { 
    blinker = null; 
} 
public void run() { 
    Thread thisThread = Thread.currentThread(); 
    while (blinker == thisThread) { 
     try { 
      thisThread.sleep(interval); 
     } catch (InterruptedException e){ 
     } 
     repaint(); 
    } 
}