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

Time:07-26

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.

CodePudding user response:

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().

  • Related