//mainActivity
package com.demo.vedio;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class MainActivity extends Activity {
private MediaPlayer player;
private SurfaceView sv;
SurfaceHolder holder;
int progress = 0; //定义播放进度
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv = (SurfaceView) findViewById(R.id.sv);
//获取surfaceview的控制器
holder = (SurfaceHolder) sv.getHolder();
holder.addCallback(new Callback() {
@Override
//在surfaceview销毁时调用
public void surfaceDestroyed(SurfaceHolder holder) {
if(player != null){
//停止之前先保存播放进度
progress = player.getCurrentPosition();
player.stop(); //停止
player.release(); //释放资源
player = null;
}
}
//在surfaceview创建时调用
@Override
public void surfaceCreated(SurfaceHolder holder) {
if(player == null){ //判断play是否为空,空就创建
player = new MediaPlayer();
//player.reset();
try {
player.setDataSource("mnt/sdcard/2.3gp");
//指定视频播放在哪个surfaceview
player.setDisplay(holder); //返回的是一个Surfaceholder
player.prepare();
//跳转到上一次停止的地方继续播放
player.seekTo(progress);
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
//在surfaceview改变时调用
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
});
}
}
//布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<SurfaceView
android:id="@+id/sv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
//MainActivit文件
package com.demo.videoview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.VideoView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView vv = (VideoView) findViewById(R.id.vv);
vv.setVideoPath("sdcard/2.3gp");
vv.start();
}
}
//布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<VideoView
android:id="@+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>