当用户离开活动时,我想停止线程。这听起来很简单,但没有一个函数,我试过了,它是有效的。
我用代码开始了这个活动
lovi = new Intent(getApplicationContext(), listoverview.class);
lovi.putExtra("reloadAll", true);
startActivity(lovi);在列表概述的onCreate中,我使用以下代码启动线程
rlMF.start();rlMF看起来像这样:
public Thread rlMF = new Thread(new Runnable() {
public void run() {
reloadMissingFiles();
}
});我尝试在onPause中使用rlMF.stop()、.interrupt()、.suspend。没有什么能阻止它。
发布于 2012-07-10 15:35:49
你必须添加一些标志来阻止它。通过其他方式停止线程可能会产生可怕的后果,比如资源泄漏。
例如:
volatile boolean activityStopped = false;创建runnable时:
public Thread rlMF = new Thread(new Runnable() {
public void run() {
while (!activityStopped) {
// reloadMissingFiles() should check the flag in reality
reloadMissingFiles();
}
}
});在onPause()中:
protected void onPause(){
super.onPause();
activityStopped = true;
}发布于 2012-07-10 15:29:15
使用Android处理程序
Runnable r = new Runnable()
{
public void run()
{
// do stuff
handler.post(this);
}
};
handler.post(r);在onPause中:
protected void onPause(){
super.onPause();
handler.removeCallbacks();
}发布于 2012-07-10 15:30:05
您可以调用AsyncTask的cancel(boolean mayInterruptIfRunning)方法,而不是尝试使用AsyncTask。您还应该记住,如果使用cancel(true),则捕获可能抛出的InteruptedException。
这里是关于Threads,Handlers和AsyncTask的a usefull tutorial,可能会对你有所帮助。
https://stackoverflow.com/questions/11408453
复制相似问题