先看代码
public class SurfaceViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new MySurfaceView(this));
}
}
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder surfaceHolder;
private Paint paint;
public MySurfaceView(Context context) {
super(context);
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
paint = new Paint();
paint.setColor(Color.RED);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i("Logzy", Thread.currentThread().getName() + ":surfaceCreated");
myDraw();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i("Logzy", Thread.currentThread().getName() + ":surfaceChanged");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("Logzy", Thread.currentThread().getName() + ":surfaceDestroyed");
}
private void myDraw() {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawRect(0, 0, 100, 100, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
Log.i("Logzy", Thread.currentThread().getName() + ":onWindowFocusChanged");
}
}
重写了surfaceCreated,surfaceChanged,surfaceDestroyed,onWindowFocusChanged这几个方法.运行程序,结果是:
04-13 08:56:03.111 13682-13682/edu.cgxy.surfaceview I/Logzy﹕ main:surfaceCreated
04-13 08:56:03.111 13682-13682/edu.cgxy.surfaceview I/Logzy﹕ main:surfaceChanged
04-13 08:56:03.141 13682-13682/edu.cgxy.surfaceview I/Logzy﹕ main:onWindowFocusChanged
再把程序切换到后台,结果是
04-13 08:59:49.661 13682-13682/edu.cgxy.surfaceview I/Logzy﹕ main:onWindowFocusChanged
04-13 08:59:49.791 13682-13682/edu.cgxy.surfaceview I/Logzy﹕ main:surfaceDestroyed