surfaceView的特点:
1. 使用了双缓冲的机制,两个线程交替执行
解释:何为双缓冲,一个线程在计算,另外一个线程就在渲染。
2. surfaceView这个控件非常的消耗资源,所以,系统不会再一上来的时候就马上去绘制这个控件.该控件,会等到其他界面资源渲染好之后,才会渲染。所以,一上来就对该控件进行操作。是会报空指针的。因此解决的方案就是添加监听就好。
SurfaceHolder holder = sv.getHolder();
holder.addCallback(new Callback() {
//销毁时候调用
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG, "surfaceDestroyed---");
}
//创建时候调用
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated---");
new Thread(){
@Override
public void run() {
//SystemClock.sleep(10000000);
//得到控制器
SurfaceHolder holder = sv.getHolder();
int radius = 5;
for (int i = 0; i < 100; i++) {
Canvas canvas = holder.lockCanvas();
canvas.drawColor(Color.BLACK);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(200, 200, radius+i, paint);
holder.unlockCanvasAndPost(canvas);
SystemClock.sleep(10);
}
}
}.start();
}
//状态发生改变时调用
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(TAG, "surfaceChanged---");
}
});
VideoView的父类是就是SurfaceView。videoView只是增强了一下SurfaceView添加了一些可见的界面。
//1. 有控件
VideoView vv = (VideoView) findViewById(R.id.vv);
//定义多媒体控制器
MediaController controller = new MediaController(this);
//设置控制的是哪一个view
controller.setAnchorView(vv);
//设置vv的控制器是谁
vv.setMediaController(controller);
//2. 关联视频
vv.setVideoPath("/mnt/sdcard/oppo.3gp");
//3. 播放
vv.start();
既然videoView是surfaceView的子类。所以我们在制作播放器的时候。就是增强surfaceView。
//1. 有控件
SurfaceView sv = (SurfaceView) findViewById(R.id.sv);
//得到控制器
SurfaceHolder holder = sv.getHolder();
holder.addCallback(new Callback() {
private MediaPlayer mediaPlayer;
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
int position = mediaPlayer.getCurrentPosition();
SharedPreferences sp = getSharedPreferences("music", 0);
sp.edit().putInt("position", position).commit();
mediaPlayer.release();
mediaPlayer = null;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
//播放视频
try {
int position = getSharedPreferences("music", 0).getInt("position", 0);
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("/mnt/sdcard/oppo.3gp");
mediaPlayer.prepare();
//显示画面
mediaPlayer.setDisplay(holder);
//跳转到上一次播放位置
mediaPlayer.seekTo(position);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
});