Skip to content Skip to sidebar Skip to footer

Android, Run Code Only After The UI Has Been Rendered For An Activity

I know this question is on here many times, but the answer that works in all of those cases does not work for mine. When the activity starts I am taking a screenshot of the screen.

Solution 1:

You could just grab the top decor view using Window.getDecorView() and then use post(Runnable) on it. Using the decor view results in reusable code that can be run in any application as it does not depend on some specific View element being a part of the inflated layout.

The call will result in your Runnable being placed in the message queue to be run on the UI thread, so do not run long operations in the Runnable to avoid blocking the UI thread.


Simple implementation - Kotlin

// @Override protected void onCreate(Bundle savedInstanceState) {

    window.decorView.post {
        // TODO your magic code to be run
    }


Simple implementation - Java

// @Override protected void onCreate(Bundle savedInstanceState) {

    getWindow().getDecorView().post(new Runnable() {

        @Override
        public void run() {
            // TODO your magic code to be run
        }

    });

Post a Comment for "Android, Run Code Only After The UI Has Been Rendered For An Activity"