您的目标是从onPause
. 有几种方法可以做到这一点,但本质上,您需要在reloadMissingFiles
.
选项1
您可以像以前一样使用布尔标志 - 您需要将其声明为volatile
确保更改在线程之间可见:
private volatile boolean activityStopped = false;
public void reloadMissingFiles() {
while (!activityStopped) {
//load small chunks so that the activityStopped flag is checked regularly
}
}
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles(); //will exit soon after activityStopped has been set to false
}
});
protected void onPause() {
//This will stop the thread fairly soon if the while loop in
//reloadMissingFiles is fast enough
activityStopped = true;
super.onPause();
}
选项 2(更好的方法)
我不知道你在做什么reloadMissingFiles
,但我想这是某种 I/O 操作,通常是可中断的。然后,您可以制定一个中断策略,在捕获到 InterruptedException 后立即停止:
public void reloadMissingFiles() {
try {
//use I/O methods that can be interrupted
} catch (InterruptedException e) {
//cleanup specific stuff (for example undo the operation you started
//if you don't have time to complete it
//then let the finally block clean the mess
} finally {
//cleanup (close the files, database connection or whatever needs to be cleaned
}
}
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles(); //will exit when interrupted
}
});
protected void onPause() {
runner.interrupt(); //sends an interruption signal to the I/O operations
super.onPause();
}
注意:您也可以阅读这篇文章以获得更深入的版本。