<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/ll1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <VideoView android:id="@+id/video" android:background="@drawable/ic_launcher" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center"/> </LinearLayout>
package com.example.test; import java.io.File; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.os.Environment; import android.widget.MediaController; import android.widget.Toast; import android.widget.VideoView; public class MainActivity extends Activity{ private VideoView video; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); video=(VideoView)findViewById(R.id.video); //判断sd卡是否存在 String SdPath="/sdcard"; if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ //如果SD卡存在,则获取根目录 SdPath=Environment.getExternalStorageDirectory().toString(); } File file=new File(SdPath+"/Movies/my.mp4");//获取SD卡上要播放的文件 MediaController mc=new MediaController(MainActivity.this); if(file.exists()){//判断要播放的视频是否存在 video.setVideoPath(file.getAbsolutePath());//指定要播放的视频 video.setMediaController(mc);//设置VedioView与MediaController相关联 video.requestFocus();//让VedioView获得焦点 try { video.getBackground().setAlpha(0);//将背景图片设为透明 video.start();//开始播放视频 } catch (Exception e) { // TODO: handle exception } //为VideoView添加完成事件监听器 video.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //弹出消息提示框显示播放完毕 Toast.makeText(MainActivity.this, "视频播放完毕", Toast.LENGTH_SHORT).show(); } }); }else{ //弹出消息提示框显示文件不存在 Toast.makeText(MainActivity.this, "要播放的视频文件不存在!", Toast.LENGTH_SHORT).show(); } } }
<activity android:name=".MainActivity" android:screenOrientation="landscape" android:label="@string/app_name" > ......
运行之后的效果如图
转载请注明出处:http://blog.csdn.net/acmman/article/details/46551075