I’m developing a live wallpaper, and I have a problem that has been bugging me for a while. My live wallpaper crashes when it’s turned into landscape and then back to portrait several times in a row.
The LogCat shows the following error:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException
at android.view.Surface.unlockCanvasAndPost(Native >Method)
at com.android.internal.view.BaseSurfaceHolder.unlockCanvasAndPost(BaseSurfaceHolder.java:215)
at livewallpaper.LiveWallpaper$CatWallEngine.draw(LiveWallpaper.java:167)….
This is the code:
public void draw() {
SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
paint = new Paint();
try {
c = holder.lockCanvas();
if (c != null ) {
//drawing code goes here
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
mHandler.removeCallbacks(mUpdateDisplay);
if (mVisible) {
mHandler.postDelayed(mUpdateDisplay, 50);
}
The line 167 is the holder.unlockCanvasAndPost(c); line.
I’ve read elsewhere that trying to unlock the canvas that is not locked might cause this error, but I’ve checked that and that’s not the problem: canvas gets locked every time before trying to unlock it.
After I added the try/catch block inside my ‘finally’ block, the live wallpaper stopped crashing.
My ‘finally’ block looks like this now: