SurfaceView
- 使用双缓冲技术
- 是个重量级的组件
- 只要不可见,就不会创建,可见时,才会创建
- 只要不可见,就会销毁
SurfaceView一旦不可见,就会被销毁,一旦可见,就会被创建,销毁时停止播放,再次创建时再开始播放
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView; public class MainActivity extends Activity {
private MediaPlayer player;
static int currentPosition; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); SurfaceView sv = (SurfaceView) findViewById(R.id.sv);
// 拿到surfaceview的控制器
final SurfaceHolder sh = sv.getHolder();
//给SurfaceHolder设置CallBack,类似于侦听,可以知道SurfaceView的状态
sh.addCallback(new Callback() {
// surfaceView销毁时调用
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 每次surfaceview销毁时,同时停止播放视频
if (player != null) {
currentPosition = player.getCurrentPosition();
player.stop();
player.release();
player = null;
}
} // surfaceView创建时调用
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 每次surfaceView创建时才去播放视频
if (player == null) {
player = new MediaPlayer();
player.reset();
try {
player.setDataSource("sdcard/2.3gp");
player.setDisplay(sh);
player.prepare();
player.start();
player.seekTo(currentPosition);
} catch (Exception e) {
e.printStackTrace();
}
} } // surfaceView结构改变时调用
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
}
}