你的目標是從中斷線程。有幾種方法可以實現,但基本上,您需要在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();
}
注意:您還可以閱讀this article進行更深入的版本的它。
你想達到什麼目的?當onPause被調用時,你是否試圖中斷你的線程? – assylias 2012-07-10 09:59:28
是的,這就是我想要做的... – Styler2go 2012-07-10 10:42:09
看到我的答案關於各種方法來做到這一點。 – assylias 2012-07-10 11:02:14