简体   繁体   English

无法使用Thread.interrupt在Android上停止进度栏

[英]cannot stop progress bar on Android using Thread.interrupt

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. 我有一个简单的进度栏,但Thread.interrupt不会停止线程。 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 如何在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. 换句话说,为什么Thread.interrupt不会停止线程。

thx! 谢谢!

Why don't you try the following 你为什么不尝试以下

Thread background = new Thread() { public void run() { 线程背景=新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(); 

It doesn't work because you're catching InterruptedException and ignoring it. 它不起作用,因为您正在捕获InterruptedException并忽略了它。 The thread is no longer interrupted after the exception is thrown. 引发异常后,线程不再被中断。 (See this Q&A .) But k0sh is right, you should use an AsyncTask . (请参阅此问答) 。但是k0sh是正确的,您应该使用AsyncTask

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM