《Hello Andriod》中第五章介绍了andriod视频播放内容,但不全。
先贴代码:
package com.example.video;
import java.io.File;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;
public class Video extends Activity {
private VideoView video;
MediaController mediaco;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
video = (VideoView) findViewById(R.id.video);
mediaco = new MediaController(this);
File file = new File("/mnt/sdcard/Gee.mp4");
if(file.exists())
{
video.setVideoPath(file.getAbsolutePath());
video.setMediaController(mediaco);
mediaco.setMediaPlayer(video);
video.requestFocus();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.video, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_video,
container, false);
return rootView;
}
}
}
布局文件如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.video.Video" tools:ignore="MergeRootFrame" > <VideoView android:id="@+id/video" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center"/> </FrameLayout>
发现该程序不可以真机测试运行,因为测试时sd卡是不能读取的,但是程序需要读取sd卡中的视频文件(Gee.mp4是事先拷贝到sd中),故将程序安装好后,断开数据线后跑程序就没问题了。
ps:视频播放时,若旋转屏幕会导致视频从头播放; 解决办法:调用onRetainNonConfigurationInstance()保存onCreate()中的数据,调用getLastNonConfigurationInstance()恢复数据。