Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I find when Android Java thread finishes its task?

I have start a thread in my Android Apllication – in Java like bellow

new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Log.d(TAG, "startThread: " + i);
                        if (i == 5) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    buttonStartThread.setText("50%");
                                }
                            });
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

How I can find when the thread finishes its task when written like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Easiest way would be to have the Runnable call some method when it completes, like this:

    for (int i = 0; i < 10; i++) {
        try {
            ...
        } catch (InterruptedException e) {
            ...
        }
    }
    // notify that I am done
    notifyThreadDone();

private void notifyThreadDone() {
    // Do whatever you want to do here
}

Note that notifyThreadDone() will be called on the other Thread, not on the main (UI) thread. If you want to do something with UI elements (display something, etc.), make sure that you call notifyThreadDone() on the main (UI) thread by wrapping the call in runOnUiThread().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading