问题描述
我知道这个问题已经很多次了,但是在所有这些情况下都有效的答案不适用于我的情况.活动开始时,我正在截取屏幕截图.我在onCreate的底部执行代码.它可以很好地运行4次,共5次,而第5次屏幕尚未呈现,您将获得黑色屏幕截图.
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.
我的解决方法是在onCreate末尾启动的AsyncTask中执行屏幕截图代码.如果我将200ms的睡眠时间设为10,则有9次有效. 500毫秒的睡眠可以100%的时间获得睡眠,但是您会注意到延迟.这似乎是一个糟糕的解决方案,因为500ms是一个任意数字,可能无法在所有设备上正常工作.
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.
我怎么知道何时渲染UI,以便可以截取屏幕截图?
How can I know when the UI is rendered, so I can take my screenshot?
推荐答案
您可以使用 Window.getDecorView(),然后使用在其上张贴(Runnable).使用装饰视图会导致可重复使用的代码在任何应用程序中运行,因为它不依赖于某些特定的视图元素是展开式布局的一部分.
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.
该调用将导致您的 Runnable 放置在消息中队列要在UI线程上运行,因此请勿在Runnable中运行长时间的操作,以免阻塞UI线程.
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
}
});
这篇关于Android,仅在呈现活动的UI后才运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!