理解SurfaceFlinger在Android中的作用
package cn.juwatech.surfaceflingerdemo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceFlingerDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MySurfaceView(this));
}
// 自定义SurfaceView
class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private DrawThread drawThread;
public MySurfaceView(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
drawThread = new DrawThread(holder, context);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
drawThread.setRunning(true);
drawThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 处理Surface尺寸的变化
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
drawThread.setRunning(false);
while (retry) {
try {
drawThread.join();
retry = false;
} catch (InterruptedException e) {
// 处理线程中断异常
}
}
}
}
// 自定义绘图线程
class DrawThread extends Thread {
private SurfaceHolder surfaceHolder;
private Context context;
private boolean isRunning;
private Paint paint;
public DrawThread(SurfaceHolder holder, Context context) {
surfaceHolder = holder;
this.context = context;
isRunning = false;
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
}
public void setRunning(boolean run) {
isRunning = run;
}
@Override
public void run() {
Canvas canvas;
while (isRunning) {
canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
// 在Canvas上绘制内容
canvas.drawColor(Color.WHITE);
canvas.drawRect(100, 100, 300, 300, paint);
}
} finally {
if (canvas != null) {
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}