Android开发之MediaPlayer和SurfaceView组成视频播放器
SurfaceView
- 使用双缓冲技术
- 是个重量级的组件
- 只要不可见,就不会创建,可见时,才会创建
- 只要不可见,就会销毁
SurfaceView一旦不可见,就会被销毁,一旦可见,就会被创建,销毁时停止播放,再次创建时再开始播放
1 import android.app.Activity; 2 import android.media.MediaPlayer; 3 import android.os.Bundle; 4 import android.view.SurfaceHolder; 5 import android.view.SurfaceHolder.Callback; 6 import android.view.SurfaceView; 7 8 public class MainActivity extends Activity { 9 private MediaPlayer player; 10 static int currentPosition; 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 17 SurfaceView sv = (SurfaceView) findViewById(R.id.sv); 18 // 拿到surfaceview的控制器 19 final SurfaceHolder sh = sv.getHolder(); 20 //给SurfaceHolder设置CallBack,类似于侦听,可以知道SurfaceView的状态 21 sh.addCallback(new Callback() { 22 // surfaceView销毁时调用 23 @Override 24 public void surfaceDestroyed(SurfaceHolder holder) { 25 // 每次surfaceview销毁时,同时停止播放视频 26 if (player != null) { 27 currentPosition = player.getCurrentPosition(); 28 player.stop(); 29 player.release(); 30 player = null; 31 } 32 } 33 34 // surfaceView创建时调用 35 @Override 36 public void surfaceCreated(SurfaceHolder holder) { 37 // 每次surfaceView创建时才去播放视频 38 if (player == null) { 39 player = new MediaPlayer(); 40 player.reset(); 41 try { 42 player.setDataSource("sdcard/2.3gp"); 43 player.setDisplay(sh); 44 player.prepare(); 45 player.start(); 46 player.seekTo(currentPosition); 47 } catch (Exception e) { 48 e.printStackTrace(); 49 } 50 } 51 52 } 53 54 // surfaceView结构改变时调用 55 @Override 56 public void surfaceChanged(SurfaceHolder holder, int format, 57 int width, int height) { 58 } 59 }); 60 } 61 }
直面挑战,躬身入局