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?
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.
// @Override protected void onCreate(Bundle savedInstanceState) {
window.decorView.post {
// TODO your magic code to be run
}
// @Override protected void onCreate(Bundle savedInstanceState) {
getWindow().getDecorView().post(new Runnable() {
@Override
public void run() {
// TODO your magic code to be run
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With