How can I disable a thread that is not in use?

I am struggling with an Android app to handle new things for me. I created a thread, a persistent message subscriber, in my application, waiting for messages from the server in the background. When I exit my application, the thread is still running. Actually the thread tries to connect over and over again when it fails to connect to the server. So I want to check that my application is shutdown or is still alive, otherwise I want my application to send some message to the thread to stop it before it goes down.

What methods can be used in Android? Please let me hear your knowledge. Thanks in advance.

+3


source to share


2 answers


you cannot destroy ... only android will stop the thread when needed .. you cannot stop it or kill it .. instead try like this .. set some flag on the thread .. check when it should work and when it should stop .. like this ...

 void run()
{
 while(bool){
   //My code 
 }
 }

      



now on stopping your activity change the bool value to false.

@Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
bool=false
   }

      

0


source


yes, there is a simple template for this. you start your flow in onResume()

and stop it at onPause()

.

in your runnable thread, you have a loop like <

@Override
public void run() {
    while (mRunning) {
      // re-try server
    }
}

      

in your activity, override onResume () as,

@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 executed.

in general, you follow this pattern for any listener you register or start. tune it on onResume()

and tear it off at onPause()

.

+2


source







All Articles