public class MainActivity extends Activity { private EditText nameText; private String path; private MediaPlayer mediaPlayer; private SurfaceView surfaceView;//此组件用于播放视频 private boolean pause; private int position; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mediaPlayer = new MediaPlayer(); nameText = (EditText) this.findViewById(R.id.filename); surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView); //把输送给surfaceView的视频画面,直接显示到屏幕上,不要维持它自身的缓冲区 surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); surfaceView.getHolder().setFixedSize(176, 144); surfaceView.getHolder().setKeepScreenOn(true); //当SurfaceView所在的Activity离开了前台,SurfaceView会被destroy,当Activity //重新回到前台时,SurfaceView会被重新创建,创建时在onresume()方法之后,所以此时会出现黑屏,使用下面的方法解决 surfaceView.getHolder().addCallback(new SurfaceCallback()); } private final class SurfaceCallback implements Callback{ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceCreated(SurfaceHolder holder) { //重新播放 if(position>0 && path!=null){ play(position); position = 0; } } public void surfaceDestroyed(SurfaceHolder holder) { //停止播放 if(mediaPlayer.isPlaying()){ position = mediaPlayer.getCurrentPosition(); mediaPlayer.stop(); } } } @Override protected void onDestroy() { mediaPlayer.release(); mediaPlayer = null; super.onDestroy(); } public void mediaplay(View v){ switch (v.getId()) { case R.id.playbutton://处理播放按钮点击事件 String filename = nameText.getText().toString(); if(filename.startsWith("http")){//播放网络媒体文件,注意网络文件要是流媒体文件才可以 path = filename; play(0); }else{ File file = new File(Environment.getExternalStorageDirectory(), filename); if(file.exists()){ path = file.getAbsolutePath(); play(0); }else{ path = null; Toast.makeText(this, R.string.filenoexsit, 1).show(); } } break; case R.id.pausebutton://处理暂停按钮点击事件 if(mediaPlayer.isPlaying()){ mediaPlayer.pause(); pause = true; }else{ if(pause){ mediaPlayer.start(); pause = false; } } break; case R.id.resetbutton://处理重新播放按钮点击事件 if(mediaPlayer.isPlaying()){ mediaPlayer.seekTo(0); }else{ if(path!=null){ play(0); } } break; case R.id.stopbutton: if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); } break; } } private void play(int position) { //播放视频的方法 try { mediaPlayer.reset(); mediaPlayer.setDataSource(path);//设置数据源 mediaPlayer.setDisplay(surfaceView.getHolder());//设置SurfaceView的控对象 mediaPlayer.prepare();//缓冲 mediaPlayer.setOnPreparedListener(new PrepareListener(position));//设置缓冲监听对象,在监听对象中进行播放 } catch (Exception e) { e.printStackTrace(); } } //当缓冲完毕后会调用onPrepared()方法 private final class PrepareListener implements OnPreparedListener{ private int position; public PrepareListener(int position) { this.position = position; } public void onPrepared(MediaPlayer mp) { mediaPlayer.start();//播放视频 if(position>0) mediaPlayer.seekTo(position); } } }