使用videoView与MediController来播放视频
首先是布局文件
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.steven.testoct.VideoActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
代码文件
public class VideoActivity extends AppCompatActivity {
private VideoView videoView;
private Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
init();
}
public void init(){
uri = Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" );
videoView = (VideoView) findViewById(R.id.videoView);
videoView.setMediaController(new MediaController(this));
//播放完成回调
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText( VideoActivity.this, "播放完成了", Toast.LENGTH_SHORT).show();
}
});
//设置视频路径
videoView.setVideoURI(uri);
//开始播放
videoView.start();
}
//判断是否有断点缓存,来续播
@Override
protected void onStart() {
super.onStart();
if (!videoView.isPlaying()&&loadData(this,RandomNumber()+getDate()+"@")!="未获取") {
videoView.seekTo(Integer.valueOf(loadData(this,RandomNumber()+getDate()+"@")));
// videoView.seekTo(20000);
Log.e("Start",loadData(this,RandomNumber()+getDate()+"@"));
videoView.resume();
}
else
videoView.start();
}
//暂停函数来存储断点,在stop()中不能正确的获取断点
@Override
protected void onPause() {
videoView.pause();
saveData(this,RandomNumber()+getDate()+"@",String.valueOf(videoView.getCurrentPosition()));
Log.e("PauseTIme2",String.valueOf(videoView.getCurrentPosition()));
super.onPause();
}
//写入缓存
public static void saveData(Context context, String name, String s) {
SharedPreferences sp = context.getSharedPreferences("User", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(name, s);
editor.apply();
}
//读取缓存
public String loadData(Context context, String name) {
SharedPreferences sp = context.getSharedPreferences("User", MODE_PRIVATE);
return sp.getString(name, "未获取");
}
//获取日期
public String getDate() {
DateFormat df = new SimpleDateFormat("yyyy_MM_dd");
String s = df.format(new Date());
return String.valueOf(s);
}
//视频序号生成数
public String RandomNumber(){
return "22";
}
}
这样就可以实现最简单的播放网络视频了
* 更新10.18:添加断点续播 *