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?

Ack
  • 2,053
  • 3
  • 15
  • 17

4 Answers4

2

try this way:

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

}

and

@Override
public void onDestroy() {
    thread.interrupt();
    super.onDestroy();   
}
ρяσѕρєя K
  • 130,641
  • 51
  • 193
  • 212
0

trying to stop the thread from outside is not reliable.

I suggest to use global param using SharePreferences or Application Context, ( e.g. IS_APP_ACTIVE ) across your app
and let thread kill itself.

let me try to explain a bit...

in your Activity

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

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

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

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

in your thread

if ( !CommonUtils.isAppActive(mContext) )

just get out of the thread loop.

Yilmaz Guleryuz
  • 8,500
  • 3
  • 30
  • 43
0

I perform this way. In your activity

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

in your Thread

@Override
public void run() {
    // stop your thread
    if (interrupted()) {
        return;
    }
    // do your work
}
Peter
  • 156
  • 1
  • 6
-3

Adding finish(); should end the Activity when onDestroy() or anything else (eg. a button is pressed) is called. When you use onDestroy(), make sure super.onDestroy(); is put after everything else is called.

Kurty
  • 465
  • 2
  • 16
  • Hi, it's keep throwing InterruptedException after I added the finish() function call. Should I override something method into my Runnable class?? By the way, I have no click -1 button to your post – Ack May 11 '12 at 02:31