2015-11-14 22 views
2

我遇到了一個小問題,我不明白。我有一個簡單的進度條,但Thread.interrupt不會停止該線程。我必須把它變成一個全局變量。我想知道是否有人能夠阻止這個問題。無法停止Android上的進度條使用Thread.interrupt

我想這個線程,但我沒有工作:

How to stop a thread(progressbar) in android

這裏是與黑客

// 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(); 
現在

,我試圖阻止線程

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. 

    } 
} 
代碼

爲什麼我必須破解全球?換句話說,爲什麼Thread.interrupt不會停止線程。

thx!

+1

爲什麼不使用asyncTask? – k0sh

回答

0

你爲什麼不試試下面的

主題背景=新的Thread(){ 公共無效的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(); 
0

因爲你趕上InterruptedException它不工作,忽略它。拋出異常後線程不再中斷。 (請參閱this Q&A。)但k0sh是正確的,您應該使用AsyncTask