当我的应用开始时,用户会看到一个包含图片的ListView
。正在使用AsyncTask
下载这些图像。如果您打开该片段几次 - 图像会长时间加载项目。
据我了解,这种情况正在发生,因为正在创建大量下载AsyncTasks
并且正在下载大量重复图像,因为ListView
连续几次被调用。
我的问题是如何在片段启动时完成停止这些正在运行的线程?
答案 0 :(得分:0)
不要在再次打开片段时停止它们,而是在碎片被破坏时停止它们。
@Override
public void onDestroy(){
super.onDestroy();
task.cancel();
}
答案 1 :(得分: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();
}
}