Integrating video file in android app as app background

Well my friend, first of all you can’t set a background to your VideoView and make it play in the background of your screen.

Please follow my steps and add your effort and you should be there.

Remove your video from drawable folder and add it to raw folder. Please google how to create a raw folder. It is simple though. And put your video file inside it.

First of all, create a SurfaceView in your xml like this.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
            android:id="@+id/home_container"  
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent">

<SurfaceView 
        android:id="@+id/surface" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:paddingTop="10dip" />
</Framelayout>

Now, create a class like the one below which can implement SurfaceView,

public class YourMovieActivity extends Activity implements SurfaceHolder.Callback {
    private MediaPlayer mp = null;
    //...
  SurfaceView mSurfaceView=null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mp = new MediaPlayer();
        mSurfaceView = (SurfaceView) findViewById(R.id.surface);
        mSurfaceView.getHolder().addCallback(this);
        //...
    }
}

Now your class will ask for unimplemented methods to be added. Add those methods by just clicking on “Add unimplemented methods”

Now you will be able to see a auto generated method like this,

@Override
public void surfaceCreated(SurfaceHolder holder) {

}

And inside this method,add the below code,

@Override
public void surfaceCreated(SurfaceHolder holder) {


   Uri video = Uri.parse("android.resource://" + getPackageName() + "https://stackoverflow.com/" 
      + R.raw.your_raw_file);

    mp.setDataSource(video);
    mp.prepare();

    //Get the dimensions of the video
    int videoWidth = mp.getVideoWidth();
    int videoHeight = mp.getVideoHeight();

    //Get the width of the screen
    int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

    //Get the SurfaceView layout parameters
    android.view.ViewGroup.LayoutParams lp = mSurfaceView.getLayoutParams();

    //Set the width of the SurfaceView to the width of the screen
    lp.width = screenWidth;

    //Set the height of the SurfaceView to match the aspect ratio of the video 
    //be sure to cast these as floats otherwise the calculation will likely be 0
    lp.height = (int) (((float)videoHeight / (float)videoWidth) * (float)screenWidth);

    //Commit the layout parameters
    mSurfaceView.setLayoutParams(lp);        

    //Start video
    mp.setDisplay(holder);
    mp.start();
}

Leave a Comment