2

I am running into a minor issue that I don't understand. I have a simple progress bar but Thread.interrupt does not stop the thread. I have to hack it a global variable. I wonder if anyone can stop the issue.

I tried this thread, but did not work for me:

How to stop a thread(progressbar) in android

here's the code with the hacks

    // Start lengthy operation in a background thread
    calcThread = new Thread
    (
        new Runnable()
        {
            public void run()
            {
                Thread current = Thread.currentThread();
                //while (!current.isInterrupted()) // this does not
                while (threadLoop) // this hack works
                {
                    doWork();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {}

                    // Update the progress bar
                    mHandler.post(new Runnable() {
                        public void run() {
                            mProgress.setProgress(mProgressStatus);
                        }
                    });
                }

                Log.d(TAG, "out of thread loop");
            }
        }
    );

    calcThread.start();

now where I try to stop the thread

public void onClickAbout(View view)
{
    if (view.getId() == R.id.buttonAbout)
    {
        Log.d(TAG, "onButtonPressed");

        calcThread.interrupt(); // This does not work
        threadLoop = false; // this works.

    }
}

Why do I have to hack a global? In other words, why Thread.interrupt does not stop the thread.

thx!

Community
  • 1
  • 1
gmmo
  • 2,577
  • 3
  • 30
  • 56

2 Answers2

0

Why don't you try the following

Thread background = new Thread() { public void run() {

            try{
                for(int s=0;s<=100;s++)
                {

                    s=s+20;
                    sleep(1000);
                    progressbar.setProgress(s);
                }
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{
               //do some thing after you finish thread
            }
        }
    };
    background.start(); 
Sanjeev
  • 292
  • 2
  • 5
  • 24
0

It doesn't work because you're catching InterruptedException and ignoring it. The thread is no longer interrupted after the exception is thrown. (See this Q&A.) But k0sh is right, you should use an AsyncTask.

Community
  • 1
  • 1
Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82