Android上的Activity销毁时如何停止正在运行的线程? [英] How to stop a running thread when Activity on destroy at Android?
本文介绍了Android上的Activity销毁时如何停止正在运行的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Android活动中使用了一些线程对象.但是,当Activity销毁时,这些线程不会自行停止.我的线程停止代码如下:
I used some thread objects in my Android activity. But these threads do not stop itself when Activity on destroy. My code for thread-stopping as following:
@Override
public void onDestroy() {
super.onDestroy();
thread.interrupt();
}
以上代码不仅适用于线程对象停止,而且还会引发InterruptedException.在没有异常的情况下停止正在运行的线程的正确方法是什么?
Above code is not only working for thread object stopping but also throws an InterruptedException. What's the correct way to stop a running thread without exceptions?
线程对象抛出InterruptedException时不是错误吗?
is it not an error when thread object throws InterruptedException?
推荐答案
尝试这种方式:
volatile boolean stop = false;
public void run() {
while ( !stop ) {
log.v("Thread", "Thread running..." );
try {
Thread.sleep( 1000 );
} catch ( InterruptedException e ) {
log.v("Thread","Thread interrupted..." );
}
}
}
@Override
public void onDestroy() {
stop = true;
super.onDestroy();
}
和
@Override
public void onDestroy() {
thread.interrupt();
super.onDestroy();
}
这篇关于Android上的Activity销毁时如何停止正在运行的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文