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