Search code examples
androidmultithreadingonpause

Can't wait for thread conclusion inside onPause


I need to destroy a thread before application suspend. This is my code:

public class MyThread extends Thread
{
   public boolean mRun = false;;
   @Override
   public void run()
   {
        while (mRun)
        {
              .....
        }
    }
 }

Activity:

 @Override
 public void onPause() {
    if (mThread != null)
    {       
        mThread.mRun = false;           
        try { mThread.join(); }
        catch (InterruptedException e) { }
    }
    super.onPause();
}

But i'm pretty sure that the android system do not wait my thread conclusion and pause my application before it. How can i force thread conclusion?


Solution

  • This is the way, I used in my code meet your requirement.Hope, this will be helping you too. If you find a better solution, Please share it.

    In the below snippet, mThread is thread got created in onCreate. OnDestroy is a method that would be called before your activity destroyed.Its a best place to empty the allocated resources.

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(null != mThread) {
            Thread dummyThread = mThread;
            mThread = null;
            dummyThread.interrupt(); // Post an interrupt request to this thread.
           }
    }
    

    Cheers !