A similar question exists here but does not seem applicable to my problem: Android SurfaceHolder.unlockCanvasAndPost() does not cause redraw
See the end for the problem description, but first...
My Code
I have a very simple Activity:
...
void onCreate(...) {
setContentView(new MySurfaceView(this))
}
...
MySurfaceView.java:
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private MySurfaceViewThread task = null;
private SurfaceHolder holder = null;
public MySurfaceView(Context ctx) {
super(ctx);
holder = getHolder();
holder.addCallback(this);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
this.holder = holder; // EDIT per user2635653's answer
}
public void surfaceCreated(SurfaceHolder holder) {
this.holder = holder; // EDIT per user2635653's answer
task = new MySurfaceViewThread(holder);
task.run();
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (task != null)
task.postStop();
}
}
MySurfaceViewThread.java:
public class MySurfaceViewThread extends Thread {
private SurfaceHolder holder = null;
private int blue = 235;
private volatile boolean run = true;
public MySurfaceViewThread(SurfaceHolder h) {
holder = h;
}
@Override
public void run() {
while(run) {
if (holder.getSurface().isValid()) {
Canvas c = holder.lockCanvas();
if ((blue += 10) > 255)
blue = 0;
c.drawColor(Color.argb(255, 0, 0, blue));
holder.unlockCanvasAndPost(c);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void postStop() {
run = false;
}
}
The Problem
The surface view never updates, even though i drawColor
repeatedly. No exceptions are thrown, and the lockCanvas
and unlockCanvasAndPost
get called. However, the activity remains black after launching the app.
I noticed some interesting behavior: if I limit the number of times the while
loop runs, then after the Thread finishes, the surface view will finally draw.
I know I could copy-and-paste some working code, but my objective in asking this question is to gain a better understanding of why this doesn't work, and learn something about the Android SurfaceView
.