Florian K
Florian K

Reputation: 92

invoking callback after a thread exit - Android

I can't find a none blocking way to invoke my callback method from the main thread as my second thread exits.

I tried to use the loading.isAlive() in a while loop but it freeze the screen.

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = findViewById(R.id.load_opening_screen);
        Thread loading = new LoadingBarThread();
        loading.start();
    }

    private class LoadingBarThread extends Thread {
        @Override
        public void run() {
            for (int i=0;i<=100;i++) {
                progressBar.setProgress(i);
                try {
                    Thread.sleep(40);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void callback(){
        // start a new activity for example
    }
}

I would like to start a new activity as the ProgressBar reaches 100.

Upvotes: 0

Views: 1047

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93614

Use a Handler object and at the end of your run() function, post a Runnable to that Handler. Have the Runnable call the callback method. Handler will execute it on the thread its attached to (whatever thread it was created on).

So your new class looks like:

private class LoadingBarThread extends Thread {
   Handler handler = new Handler();
    @Override
    public void run() {
        for (int i=0;i<=100;i++) {
            progressBar.setProgress(i);
            try {
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        handler.post(new Runnable() {
           public void run() {
             callback();
           }
        });
    }
}

Upvotes: 1

Related Questions