如果表面不在前台,SurfaceHolder.lockCanvas 返回 null

发布于 2024-11-27 19:01:03 字数 510 浏览 1 评论 0原文

我目前正在 Android 中使用 LiveWallpaper 进行测试。我正在使用如下代码在画布上绘制一些内容:

final SurfaceHolder holder = getSurfaceHolder();
Canvas c = new Canvas();
c = holder.lockCanvas(); // c becomes null
c.save();
c.drawBitmap(currentBitmap);
c.restore();
holder.unlockCanvasAndPost(c);

这部分在正常情况下工作正常。但是,我有一个侦听器,只要与此服务对应的设置中的设置发生更改,它就会执行此代码。似乎每当我从设置活动执行此代码时,我都会在 c.save() 方法上获得一个 NullPointer

看来只有当Wallpaper不在前台时,holder.lockCanvas()。当它不在前景时,是否不可能绘制到该表面?

I'm currently doing a test with a LiveWallpaper in Android. I am drawing something on the canvas using code that looks something like this:

final SurfaceHolder holder = getSurfaceHolder();
Canvas c = new Canvas();
c = holder.lockCanvas(); // c becomes null
c.save();
c.drawBitmap(currentBitmap);
c.restore();
holder.unlockCanvasAndPost(c);

This part is working fine under normal circumstances. However, I have a listener that executes this code whenever a setting is changed in the Settings that correspond to this service. It seems that whenever I execute this code from the settings activity, I am getting a NullPointer on the c.save() method.

It seems that only when the Wallpaper is not in the foreground, the holder.lockCanvas(). Is it impossible to draw to this surface when it's not in the foreground?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゃ懵逼小萝莉 2024-12-04 19:01:03

这是正确的。避免这种情况的常见方法是在 onPause 或 onVisibilityChanged(false) 中取消注册侦听器,并在 onResume 或 onVisibilityChanged(true) 中重新注册,因为当画布不可见时,您不应该对设置更改做出反应。

另一种解决方案是简单地用空检查包围该代码部分,然后忘记它。不过,我建议不要这样做,因为您真正想做的是防止您的代码在不在视图中时尝试绘制到表面。

That's right. A common way to avoid this is to unregister your listener in onPause or onVisibilityChanged(false), and reregister in onResume or onVisibilityChanged(true), since you shouldn't react to settings changes when your canvas isn't visible.

Another solution would be to simply surround that section of code with a null check, and forget about it. I'd recommend against this, though, since what you really want to do is prevent your code from even attempting to draw to the surface when it's not in view.

不羁少年 2024-12-04 19:01:03

我意识到这个问题很古老,但是在遇到了同样的问题并找到了对我有用的不同答案后,我想我会为后代分享。

从表面获取画布之前检查 SurfaceHolder.getSurface.isValid() 是否有效。修复了我的空画布问题。

I realize that this question is ancient, but having had the same question and having found a different answer that worked for me, I thought I'd share for posterity.

Check if SurfaceHolder.getSurface.isValid() before getting the canvas from the surface. Fixed my null canvas issues.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文