4

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();
}

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?


is it not an error when thread object throws InterruptedException?

4

4 回答 4

2

试试这种方式:

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();   
}
于 2012-05-11T02:32:42.737 回答
0

试图从外部停止线程是不可靠的。

我建议在您的应用程序中使用 SharePreferences 或 Application Context(例如 IS_APP_ACTIVE )使用全局参数,
并让线程自行终止。

让我试着解释一下……

在您的活动中

protected void onResume() {
        super.onResume();

// isAppActive
        CommonUtils.setAppActive(mContext, true);
}

protected void onPause() {
        super.onPause();

// isAppActive
        CommonUtils.setAppActive(mContext, true);
}

在你的线程中

if ( !CommonUtils.isAppActive(mContext) )

刚刚离开线程循环。

于 2012-05-11T07:41:31.070 回答
0

我是这样表演的。在你的活动中

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

在你的线程中

@Override
public void run() {
    // stop your thread
    if (interrupted()) {
        return;
    }
    // do your work
}
于 2014-08-11T07:22:48.370 回答
-3

finish();当调用 onDestroy() 或其他任何东西(例如按下按钮)时,添加应该结束 Activity。当您使用 onDestroy() 时,请确保super.onDestroy();将其放在调用其他所有内容之后。

于 2012-05-11T02:20:20.373 回答