Vous êtes sur la page 1sur 17

Android VideoView Example

by Chryssa Aliferi on July 14th, 2014 | Filed in: Android, media

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 placeAndroid 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

Lets take a closer look:

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.

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

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.

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.

Select the Blank Activity option and press Next.

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.

You can see the structure of the project:

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 dont 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.android.com/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/layoutland/activity_main.xml , and paste the following:

activity_main.xml
01 <?xml version="1.0" encoding="utf-8"?>
02 <FrameLayout xmlns:android="http://schemas.android.com/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.

3. Creating the source code of the main Activity

Open src/com.javacodegeeks.androidvideoviewexample/AndroidVideoViewExample.java file


and paste the code below.
AndroidVideoViewExample.java
01 package com.javacodegeeks.androidvideoviewexample;
02
03
import android.app.Activity;
04
import android.app.ProgressDialog;
05
import android.content.res.Configuration;
06
import android.media.MediaPlayer;
07 import android.media.MediaPlayer.OnPreparedListener;
08 import android.net.Uri;
09
import android.os.Bundle;
10
import android.util.Log;
11
import android.widget.MediaController;
12
import android.widget.VideoView;
13
14 public 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) {
mediaControls = new
30
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
progressDialog.setTitle("JavaCodeGeeks Android Video View
39
Example");
40
// set a message for the progress bar
41
progressDialog.setMessage("Loading...");

42
43
44
45
46
47
48
49
50
51

//set the progress bar not cancelable on users' touch


progressDialog.setCancelable(false);
// show the progress bar
progressDialog.show();
try {
//set the media controller in the VideoView
myVideoView.setMediaController(mediaControls);

//set the uri of the video to be played


myVideoView.setVideoURI(Uri.parse("android.resource://" +
52
getPackageName() + "/" + R.raw.kitkat));
53
54
} catch (Exception e) {
55
Log.e("Error", e.getMessage());
56
e.printStackTrace();
57
}
58
59
myVideoView.requestFocus();
//we also set an setOnPreparedListener in order to know when the
60
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();
//if we have a position on savedInstanceState, the video
66
playback should start from here
67
myVideoView.seekTo(position);
68
if (position == 0) {
69
myVideoView.start();
70
} else {
//if we come from a resumed activity, video playback
71
will be paused
72
myVideoView.pause();
73
}
74
}
75
});
76
77
}
78
79
@Override
80
public void onSaveInstanceState(Bundle savedInstanceState) {
81
super.onSaveInstanceState(savedInstanceState);
//we use onSaveInstanceState in order to store the video playback
82
position for orientation change
savedInstanceState.putInt("Position",
83
myVideoView.getCurrentPosition());
84
myVideoView.pause();

85
86
87
88
89
90
91
92
93
94

}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//we use onRestoreInstanceState in order to play the video playback
from the stored position
position = savedInstanceState.getInt("Position");
myVideoView.seekTo(position);
}
}

Lets see in detail the code above.


We set the activity_main.xml layout and the VideoView: in our Android
Activity AndroidVideoViewExample , by:
1 setContentView(R.layout.activity_main);
2 myVideoView = (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:
1 if (mediaControls == null) {
2
mediaControls = new MediaController(AndroidVideoViewExample.this);
3 }
4 myVideoView.setMediaController(mediaControls);
The video clip starts and stops with the methods:
1
myVideoView.start();
2
myVideoView.pause();
3 myVideoView.resume();
myVideoView.seekTo(position); //when we want the video to start from a
4
certain point

We have also added a ProgressDialog that will show up until the video is completely loaded.
1 progressDialog = new ProgressDialog(AndroidVideoViewExample.this);
2 progressDialog.setTitle("JavaCodeGeeks Android Video View Example");
3 progressDialog.setMessage("Loading...");
4 progressDialog.setCancelable(false);
5
progressDialog.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.
01 myVideoView.setOnPreparedListener(new OnPreparedListener() {

02
03
04
05
06
07
08
09
10
11
12
13
14

public void onPrepared(MediaPlayer mediaPlayer) {


// close the progress bar and play the video
progressDialog.dismiss();
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
myVideoView.pause();
}
}
});

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
2 public void onSaveInstanceState(Bundle savedInstanceState) {
3
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Position",
4
myVideoView.getCurrentPosition());
5
myVideoView.pause();
6
}
And we will use onRestoreInstanceState() in order to play the video playback from the stored
position:
1 @Override
2 public 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.android.com/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
1
android:name="com.example.javacodegeeks.androidvideoviewexample
6 .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:

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

Vous aimerez peut-être aussi