分享

Android VideoView Example | Examples Java Code Geeks

 风音日和IKLS 2016-01-18

When we want to create an Android application that has an Android Activity inside of which we are planning to play a video file, we should consider in the first place Android VideoView class.

The VideoView class manages and displays a video file for applications and can load images from various sources (such as resources or content providers), taking care of computing its measurement from the video so that it can be used in any layout manager, providing display options such as scaling and tinting.

However, VideoView does not retain its full state when going into the background. In particular, it does not restore the current play state and play position. Applications should save and restore these on their own in onSaveInstanceState(Bundle) and onRestoreInstanceState(Bundle).

So, in this example, we will make an Activity that can play a 3gp video file, in portrait and landscape view, and if we pause the activity and put it in the background and later on resume it, the videoclip will be played from the play position that it was stopped.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  • JDK 1.7
  • Eclipse 4.2 Juno
  • Android SDK 4.4

Let’s take a closer look:

Want to create a kick-ass Android App?

Subscribe to our newsletter and download the Android UI Design mini-book right now!

With this book, you will delve into the fundamentals of Android UI design. You will understand user input, views and layouts, as well as adapters and fragments. Furthermore, you will learn how to add multimedia to an app and also leverage themes and styles!

 

1. Create a New Android Application Project

Tip
You may skip project creation and jump directly to the beginning of the example below.

Open Eclipse IDE and go to File → New → Project → Android Application Project.

AndroidVideoViewExample1

Specify the name of the application, the project and the package and then click Next.

AndroidVideoViewExample2

In the next window, the “Create Activity” option should be checked. The new created activity will be the main activity of your project. Then press Next button.

AndroidVideoViewExample3

In “Configure Launcher Icon” window you should choose the icon you want to have in your app. We will use the default icon of android, so click Next.

AndroidVideoViewExample4
Select the “Blank Activity” option and press Next.

AndroidVideoViewExample5

You have to specify a name for the new Activity and a name for the layout description of your app. The .xml file for the layout will automatically be created in the res/layout folder. It will also be created a fragment layout xml, that we are not going to use in this project and you can remove it if you want. Then press Finish.

AndroidVideoViewExample6

You can see the structure of the project:

AndroidVideoViewExample7

2. Creating the layout of the main Activity

We are going to make a very simple layout xml, that only consists of a FrameLayout and the VideoView. However, we should keep in mind, that the video file that we want to play, should be capable of playing either in portrait, or landscape orientation.

Tip
Generally, in Android Development, we can use as many layouts as we want, even if we want to use each one for each different resolution and every different orientation. The main idea is to have more than one main layout, with the same file name but in different res folders, each one for each different resolution and every different orientation.

In our example, we don’t want to lock our activity on one orientation and we want to be capable of video playback even if we turn our mobile device on landscape. In order to achieve this, we are going to have two different layouts, with the same name, but with different properties. First of all, we have to create the folder res/layout-land/activity_main.xml in the res folder of the project.

Open res/layout/activity_main.xml, go to the respective xml tab and paste the following:

activity_main.xml

01<?xml version="1.0" encoding="utf-8"?>
02 <FrameLayout xmlns:android="http://schemas./apk/res/android"
03   android:layout_width="fill_parent"
04   android:layout_height="fill_parent"
05   android:layout_gravity="center" >
06 
07     <VideoView
08        android:id="@+id/video_view"
09        android:layout_width="match_parent"
10        android:layout_height="wrap_content"
11        android:layout_gravity="center"/>
12 
13  </FrameLayout>

For our landscape layout we should make a new xml in the layout-land folder res/layout-land/activity_main.xml, and paste the following:

activity_main.xml

01<?xml version="1.0" encoding="utf-8"?>
02 <FrameLayout xmlns:android="http://schemas./apk/res/android"
03   android:layout_width="fill_parent"
04   android:layout_height="fill_parent"
05   android:layout_gravity="center" >
06 
07     <VideoView
08        android:id="@+id/video_view"
09        android:layout_width="wrap_content"
10        android:layout_height="match_parent"
11        android:layout_gravity="center"/>
12 
13  </FrameLayout>

In this manner, we are going to have, two different layouts, with the same name and with the same views, but with different properties. In this way, our activity will choose the right layout for the exact need. For instance, when we turn our mobile device in landscape mode, the activity will use the res/layout-land/activity_main.xml from the layout-land folder and adjust the video in the right proportions.

Tip
In fact, the differences between the two layouts, can be found only in the layout_width and layout_height of the VideoView. This minor change can also be done programmatically, if we use the onOrientationChanged() method from OrientationEventListener.

Also, do not forget to insert a video clip in the res/raw folder of the project. We have dragged and dropped the kitkat.3gp file.

AndroidVideoViewExample8

3. Creating the source code of the main Activity

Open src/com.javacodegeeks.androidvideoviewexample/AndroidVideoViewExample.java file and paste the code below.

AndroidVideoViewExample.java

01package com.javacodegeeks.androidvideoviewexample;
02 
03import android.app.Activity;
04import android.app.ProgressDialog;
05import android.content.res.Configuration;
06import android.media.MediaPlayer;
07import android.media.MediaPlayer.OnPreparedListener;
08import android.net.Uri;
09import android.os.Bundle;
10import android.util.Log;
11import android.widget.MediaController;
12import android.widget.VideoView;
13 
14public class AndroidVideoViewExample extends Activity {
15 
16    private VideoView myVideoView;
17    private int position = 0;
18    private ProgressDialog progressDialog;
19    private MediaController mediaControls;
20 
21    @Override
22    protected void onCreate(final Bundle savedInstanceState) {
23        super.onCreate(savedInstanceState);
24 
25        // set the main layout of the activity
26        setContentView(R.layout.activity_main);
27 
28        //set the media controller buttons
29        if (mediaControls == null) {
30            mediaControls = new MediaController(AndroidVideoViewExample.this);
31        }
32 
33        //initialize the VideoView
34        myVideoView = (VideoView) findViewById(R.id.video_view);
35 
36        // create a progress bar while the video file is loading
37        progressDialog = new ProgressDialog(AndroidVideoViewExample.this);
38        // set a title for the progress bar
39        progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
40        // set a message for the progress bar
41        progressDialog.setMessage("Loading...");
42        //set the progress bar not cancelable on users' touch
43        progressDialog.setCancelable(false);
44        // show the progress bar
45        progressDialog.show();
46 
47        try {
48            //set the media controller in the VideoView
49            myVideoView.setMediaController(mediaControls);
50 
51            //set the uri of the video to be played
52            myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.kitkat));
53 
54        } catch (Exception e) {
55            Log.e("Error", e.getMessage());
56            e.printStackTrace();
57        }
58 
59        myVideoView.requestFocus();
60        //we also set an setOnPreparedListener in order to know when the video file is ready for playback
61        myVideoView.setOnPreparedListener(new OnPreparedListener() {
62         
63            public void onPrepared(MediaPlayer mediaPlayer) {
64                // close the progress bar and play the video
65                progressDialog.dismiss();
66                //if we have a position on savedInstanceState, the video playback should start from here
67                myVideoView.seekTo(position);
68                if (position == 0) {
69                    myVideoView.start();
70                } else {
71                    //if we come from a resumed activity, video playback will be paused
72                    myVideoView.pause();
73                }
74            }
75        });
76 
77    }
78 
79    @Override
80    public void onSaveInstanceState(Bundle savedInstanceState) {
81        super.onSaveInstanceState(savedInstanceState);
82        //we use onSaveInstanceState in order to store the video playback position for orientation change
83        savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
84        myVideoView.pause();
85    }
86 
87    @Override
88    public void onRestoreInstanceState(Bundle savedInstanceState) {
89        super.onRestoreInstanceState(savedInstanceState);
90        //we use onRestoreInstanceState in order to play the video playback from the stored position
91        position = savedInstanceState.getInt("Position");
92        myVideoView.seekTo(position);
93    }
94}

Let’s see in detail the code above.

We set the activity_main.xml layout and the VideoView: in our Android Activity AndroidVideoViewExample, by:

1setContentView(R.layout.activity_main);
2myVideoView = (VideoView) findViewById(R.id.video_view);

and if we want to use media controls, such as play, pause and forward, we have to add MediaController class by adding the component in the Activity:

1if (mediaControls == null) {
2      mediaControls = new MediaController(AndroidVideoViewExample.this);
3}
4myVideoView.setMediaController(mediaControls);

The video clip starts and stops with the methods:

1myVideoView.start();
2myVideoView.pause();
3myVideoView.resume();
4myVideoView.seekTo(position); //when we want the video to start from a certain point

We have also added a ProgressDialog that will show up until the video is completely loaded.

1progressDialog = new ProgressDialog(AndroidVideoViewExample.this);
2progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
3progressDialog.setMessage("Loading...");
4progressDialog.setCancelable(false);
5progressDialog.show();
Tip
You can see more about the android ProgressDialog in our previous example: Android ProgressDialog Example.

Also, in order to catch the loaded video file event, we have added an OnPreparedListener on our VideoView.

01myVideoView.setOnPreparedListener(new OnPreparedListener() {
02      public void onPrepared(MediaPlayer mediaPlayer) {
03 
04      // close the progress bar and play the video
05      progressDialog.dismiss();
06      myVideoView.seekTo(position);
07 
08      if (position == 0) {
09              myVideoView.start();
10      } else {
11              myVideoView.pause();
12      }
13   }
14});

Here is a bit more tricky point. If you compile and run the application at this point, the video clip will be played, but if you rotate your mobile device, or if you put the activity in the background and then resume, the video will restart. In order to prevent this awkward behavior, we are going to insert two methods, that will help us retain the state of the video file, when rotating and resuming our activity. The methods that we are going to use are: onSaveInstanceState() and onRestoreInstanceState().

We will use onSaveInstanceState() in order to store the video playback position:

1@Override
2public void onSaveInstanceState(Bundle savedInstanceState) {
3      super.onSaveInstanceState(savedInstanceState);
4      savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());
5      myVideoView.pause();
6}

And we will use onRestoreInstanceState() in order to play the video playback from the stored position:

1@Override
2public void onRestoreInstanceState(Bundle savedInstanceState) {
3      super.onRestoreInstanceState(savedInstanceState);
4      position = savedInstanceState.getInt("Position");
5      myVideoView.seekTo(position);
6}

4. Android Manifest

In order to make our activity rotetable, we have to add to the activity tag in the AndroidManifest.xml the following line: android:configChanges="orientation"

AndroidManifest.xml

01<?xml version="1.0" encoding="utf-8"?>
02<manifest xmlns:android="http://schemas./apk/res/android"
03    package="com.example.javacodegeeks.androidvideoviewexample"
04    android:versionCode="1"
05    android:versionName="1.0" >
06 
07    <uses-sdk
08        android:minSdkVersion="8"
09        android:targetSdkVersion="19" />
10 
11    <application
12        android:allowBackup="true"
13        android:icon="@drawable/ic_launcher"
14        android:label="@string/app_name">
15        <activity
16            android:name="com.example.javacodegeeks.androidvideoviewexample.AndroidVideoViewExample"
17            android:label="@string/app_name"
18            android:configChanges="orientation">
19            <intent-filter>
20                <action android:name="android.intent.action.MAIN"/>
21                <category android:name="android.intent.category.LAUNCHER"/>
22            </intent-filter>
23        </activity>
24    </application>
25</manifest>        

5. Build, compile and run

When we build, compile and run our project, the main Activity should look like this:

AndroidVideoViewUI1

AndroidVideoViewUI2

You should click and play, stop, forward the video clip, and also rotate your mobile device without stopping or restarting the playback. You can also put the activity in the background, and then resume it, without restarting the video!

Download the Eclipse Project

This was an example of Android VideoView.

Download  
You can download the full source code of this example here: VideoView.zip

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多