如果表面不在前台,SurfaceHolder.lockCanvas 返回 null
我目前正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正确的。避免这种情况的常见方法是在 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.
我意识到这个问题很古老,但是在遇到了同样的问题并找到了对我有用的不同答案后,我想我会为后代分享。
从表面获取画布之前检查 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.