code:
package com.example.media_play;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.Window;
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SurfaceView sfv = (SurfaceView) findViewById(R.id.sfv);
SurfaceHolder holder = sfv.getHolder();
holder.addCallback(new Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mediaPlayer!=null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {;
mediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor fd = getAssets().openFd("GEM.mp4");
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mediaPlayer.prepare();
mediaPlayer.setDisplay(holder);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();}}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
});
/*try {
AssetFileDescriptor fd = getAssets().openFd("GEM.mp4");
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
xml:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.media_play.MainActivity" >
<SurfaceView
android:id="@+id/sfv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>