android - 如何在 Android 上销毁 Activity 时停止正在运行的线程?

标签 android

我在我的 Android Activity 中使用了一些线程对象。但是当 Activity 销毁时,这些线程不会自行停止。我的线程停止代码如下:

@Override
public void onDestroy() {
    super.onDestroy();
    thread.interrupt();
}

以上代码不仅适用于线程对象停止,而且还会抛出 InterruptedException。无异常地停止正在运行的线程的正确方法是什么?


thread对象抛出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 - 如何在 Android 上销毁 Activity 时停止正在运行的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10544515/

相关文章:

android - 显示不支持的自定义属性的错误

android - 按下后退时强制 EditText 失去焦点

android - 我的 Flash 应用程序如何才能正确适合所有 Android 设备?

android - 无法从 Kotlin 1.2.10 解析 lateinitVar 以使用 isInitialized

android - NativeScript Vue + FaSTLane - 自定义 iOS/Android 项目路径?

android - 使用带有 Gradle 的 Android API 的 Java 模块

android - java.lang.IllegalArgumentException : Failed to find configured root that contains "insert app directory path here" 异常

javascript - 错误 : 180: EXCEPTION thrown ('dev!' ): - and ERROR:> aqsrv> 70: Exception caught in (null) - Error -1

android - 如何覆盖 backpress 不杀死 Activity ?

android - 如何在 Android 上使用 TextWatcher 处理回车键