Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android, run code only after the UI has been rendered for an activity

Tags:

android

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. I execute my code at the bottom of the onCreate. It works great 4 our of 5 times and the 5th time the screen has not rendered yet and you get a black screenshot.

My workaround is to execute the screenshot code in an AsyncTask that is started at the end of onCreate. If I put a 200ms sleep the it works 9 out of 10 times. A 500ms sleep gets it 100% of the time but you can notice the delay. This also seems like a terrible solution because that 500ms is an arbitrary number that may not work across all devices.

How can I know when the UI is rendered, so I can take my screenshot?

like image 944
Cameron McBride Avatar asked Nov 22 '14 18:11

Cameron McBride


1 Answers

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
        }

    });
like image 72
Valter Jansons Avatar answered Nov 16 '22 03:11

Valter Jansons