Android: 如何使用 VirtualDisplay 在 WallpaperService 中托管 WebView?

Android: How to use a VirtualDisplay to host a WebView in a WallpaperService?

背景

我有一个基于网络的动画,我已经将它变成了一个带有动态壁纸的 Android 应用程序:

http://pixfabrik.com/livingworlds/

我已通过创建 WebView 并定期将其内容复制到 WallpaperService 的 Surface 来完成此操作。这是相关代码:

https://gist.github.com/iangilman/71650d46384a2d4ae6387f2d4087cc37

… 下面是我如何找到该解决方案的:

Android: Use WebView for WallpaperService

这在过去四个月里运行良好,但 WebView 76 通过引入此错误破坏了动态壁纸:

https://bugs.chromium.org/p/chromium/issues/detail?id=991078

错误正在处理中,所以我对 WebView 77(定于 9 月 10 日发布)持乐观态度,并且会修复它,但如果可能的话,最好早点修复我的应用程序!

问题

在上面的错误报告中,一位 Chromium 开发人员建议改为使用 VirtualDisplay 将 WebView 连接到 WallpaperService,所以现在我正在追求它。我对 Android 比较陌生,所以我做的很天真,到目前为止还没有用。我在这里写信寻求帮助!

这是我目前拥有的(在我的引擎的 OnSurfaceChanged 中(所以我可以利用它给我的 width/height)):

@Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    super.onSurfaceChanged(holder, format, width, height);

    DisplayManager mDisplayManager = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);

    int flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY;
    int density = DisplayMetrics.DENSITY_DEFAULT;

    VirtualDisplay virtualDisplay = mDisplayManager.createVirtualDisplay("MyVirtualDisplay",
        width, height, density, holder.getSurface(), flags);

    Presentation myPresentation = new Presentation(myContext, virtualDisplay.getDisplay());

    WebView myWebView = new WebView(myPresentation.getContext());
    myWebView.loadUrl("file:///android_asset/index.html");

    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams (width, height);
    myPresentation.setContentView(myWebView, params);
}

我正在使用 Presentation 将 VirtualDisplay 连接到 WebView(根据 Chromium 开发人员的推荐),但我不确定这是否是正确的方法。

WallpaperService 运行,我没有收到任何错误,但我也看不到我的网页;只是白屏。

希望我只是在做一些愚蠢的事情……请赐教! :-)

您必须在 Presentation 对象上调用 show() 方法,否则它不会显示在虚拟显示器上。