Reputation: 1424
I am struggling with an Android app to handle things new to me. I created a thread, persistent message subscriber, in my app waiting for the messages from server in the background. When I exit my app, the thread is still working. Actually, the thread try to connect again and again when it fails to connect to server. So I want to check my app is down or stil alive, otherwise I want to make my app send some message to the thread to stop before it goes down.
What ways would be there to do that in Android?
Upvotes: 3
Views: 735
Reputation: 8079
You cannot destroy. Android will only stop the thread when required. You cannot stop or destroy it.
Instead try like this: Set some flag in thread, to check when it should run and when it should stop. Like this:
void run()
{
while(bool){
//My code
}
}
Now in onstop of your activity
Change the bool value to false
:
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
bool=false
}
Upvotes: 0
Reputation: 22637
Yes, there's a simple pattern for this. you start your thread in onResume()
, and stop it on onPause()
.
In your thread's runnable, you have a loop like,
@Override
public void run() {
while (mRunning) {
// re-try server
}
}
in your activity override onResume() like,
@Override
protected void onResume() {
super.onResume();
mRunner = new Runnable { .... );
new Thread(mRunner).start();
}
override onPause() to stop the thread,
@Override
protected void onPause() {
super.onPause();
if (mRunner != null) {
mRunner.setRunning(false);
mRunner = null;
}
}
This of course stops the loop, run()
exits, and the thread is done.
In general, you follow this pattern for any sort of listener you register or thread you start. Set it up on onResume()
, and tear down in onPause()
.
Upvotes: 2