Taha Körkem
Taha Körkem

Reputation: 906

Android finish Thread

I want to finish Thread. ProgressBar progress will 0 and Thread will close when button clicked. I used destroy(), stop(), resume(), interrupt() but doesnt work. How I can finish Thread?

 class TIME implements Runnable {
    @Override
    public void run() {

        for (int i=0; i<10; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    progressBar.setProgress(i);
                    if(i==9){Log.i("Log","Time's Up!");}
                }
            });
        }
    }
}

in onCreate()

new Thread(new TIME()).start();
ProgressBar progressBar=(ProgressBar)findViewById(R.id.progressBar1);
progressBar.setMax(2000);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          //TIME thread will finish. And progressBar.setProgress(0);
        }
    });

Upvotes: 0

Views: 1250

Answers (3)

Kasra
Kasra

Reputation: 3145

I guess I know what you are trying to achieve - but as other said before, your coding technique is a bit vague and unreadable. I guess you want to have a thread running and be able to stop the thread at some point. This is typically done in this way:

class TIME implements Runnable {
private volatile boolean isRunning = true;
    @Override
    public void run() {

       while (isRunning){
           // do some work here
       }
    }

    public void killMe(){
       isRunning=false;
    }
}

Upvotes: 1

Shai Levy
Shai Levy

Reputation: 715

I apologize for saying this but the coding technique shown feels a bit lacking and not in the spirit of the Android coding mechanisms.

Judging from the code you posted it feels like you should look on the AsyncTask documentation or on the AsyncTask section here. It has everything you need

Upvotes: 2

Gabe Sechan
Gabe Sechan

Reputation: 93561

If you mean the Thread wishes to finish itself- just exit its run function, the system will then clean it up. If you mean you want to exit it from another thread- you can't do that directly as its a very unsafe operation, you never know what the thread is doing at that time and if it may cause a resource leak or leave data in a bad state. Instead you cancel() the thread, and the thread should occasionally look and see if isCanceled() is true and if so exit its run function like above.

Upvotes: 2

Related Questions