如果表面不是在前台SurfaceHolder.lockCanvas返回null [英] SurfaceHolder.lockCanvas returns null if the surface is not in the foreground

查看:1207
本文介绍了如果表面不是在前台SurfaceHolder.lockCanvas返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前做在Android上LiveWallpaper测试。我使用code,它看起来像这样在画布上绘制的内容:

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);

这部分是在正常情况下工作正常,的。不过,我有,每当设置在对应于该服务的设置被更改执行此code的监听器。似乎每当我从设置活动执行此code,我得到一个空指针 c.save()方法。

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.

似乎只有当壁纸不是在前台,在holder.lockCanvas()。难道是不可能得出这个表面时,它不是在前台?

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?

推荐答案

这是正确的。避免这种情况的常用方法是注销中的onPause或onVisibilityChanged(假)的监听器,并在onResume或onVisibilityChanged(真)重新注册,因为你要不要设置变化做出反应时,你的画布是不可见的。

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.

另一种解决方案是简单地围绕code的那款带有空检查,并忘掉它。我建议针对这一点,虽然,因为你真正想要做的是prevent您code甚至从试图绘制到表面时,它不是在视图中。

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.lockCanvas返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆