初步了解 :
/**
* 演示SurfaceView控件的使用
* SurfaceView 单位时间内完成界面的大量多次更新
* 双缓冲机制 :
* A线程----更新ui -----后台计算---更新ui
* B线程----后台计算----更新ui ---后台计算
* 可以在子线程更新ui
*/
public class MainActivity extends Activity {
private SurfaceView sv;
boolean flag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SurfaceView) findViewById(R.id.sv);
sv.getHolder().addCallback(new Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surface被销毁了");
flag = false;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surface创建了");
flag = true;
new Thread(){
public void run() {
for(int i = 0;i<100;i++){
if(!flag){
return ;
}
SurfaceHolder holder = sv.getHolder();
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.BLACK);
int radius = 5+i;
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(250, 250, radius, paint);
holder.unlockCanvasAndPost(canvas);
SystemClock.sleep(100);
}
};
}.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("surface大小发生了变化");
}
});
}
public void click(View view){
}
}
采用surfaceview播放视频
public class MainActivity extends Activity {
private SurfaceView sv;
private MediaPlayer mediaPlayer;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SurfaceView) findViewById(R.id.sv);
sp = getSharedPreferences("config", MODE_PRIVATE);
sv.getHolder().addCallback(new Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surface被销毁");
if(mediaPlayer!=null){
int position = mediaPlayer.getCurrentPosition();
Editor editor = sp.edit();
editor.putInt("position", position);
editor.commit();
mediaPlayer.stop();
mediaPlayer.release();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surface被创建");
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/mnt/sdcard/oppo.3gp");
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.setDisplay(holder);
mediaPlayer.start();
mediaPlayer.seekTo(sp.getInt("position", 0));
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
});
}
}