20
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 Let’s 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.

Android VideoView Example

Embed Size (px)

DESCRIPTION

d

Citation preview

Android VideoView ExamplebyChryssa AliferionJuly 14th, 2014|Filed in:Android,mediaWhen 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.TheVideoViewclass 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,VideoViewdoes 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 inonSaveInstanceState(Bundle)andonRestoreInstanceState(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.4Lets take a closer look:1. Create a New Android Application ProjectTipYou may skip project creation and jump directly to thebeginning of the examplebelow.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 ActivityWe are going to make a very simple layout xml, that only consists of aFrameLayoutand theVideoView. 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.TipGenerally, 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 differentresfolders, 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 folderres/layout-land/activity_main.xmlin theresfolder of the project.Openres/layout/activity_main.xml, go to the respective xml tab and paste the following:activity_main.xml01

02

06

07

12

13

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

02

06

07

12

13

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 theres/layout-land/activity_main.xmlfrom the layout-land folder and adjust the video in the right proportions.TipIn fact, the differences between the two layouts, can be found only in thelayout_widthandlayout_heightof the VideoView. This minor change can also be done programmatically, if we use theonOrientationChanged()method fromOrientationEventListener.Also, do not forget to insert a video clip in theres/rawfolder of the project. We have dragged and dropped thekitkat.3gpfile.

3. Creating the source code of the main ActivityOpensrc/com.javacodegeeks.androidvideoviewexample/AndroidVideoViewExample.javafile and paste the code below.AndroidVideoViewExample.java01package 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

16private VideoView myVideoView;

17private int position = 0;

18private ProgressDialog progressDialog;

19private MediaController mediaControls;

20

21@Override

22protected void onCreate(final Bundle savedInstanceState) {

23super.onCreate(savedInstanceState);

24

25// set the main layout of the activity

26setContentView(R.layout.activity_main);

27

28//set the media controller buttons

29if (mediaControls == null) {

30mediaControls = new MediaController(AndroidVideoViewExample.this);

31}

32

33//initialize the VideoView

34myVideoView = (VideoView) findViewById(R.id.video_view);

35

36// create a progress bar while the video file is loading

37progressDialog = new ProgressDialog(AndroidVideoViewExample.this);

38// set a title for the progress bar

39progressDialog.setTitle("JavaCodeGeeks Android Video View Example");

40// set a message for the progress bar

41progressDialog.setMessage("Loading...");

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

43progressDialog.setCancelable(false);

44// show the progress bar

45progressDialog.show();

46

47try {

48//set the media controller in the VideoView

49myVideoView.setMediaController(mediaControls);

50

51//set the uri of the video to be played

52myVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.kitkat));

53

54} catch (Exception e) {

55Log.e("Error", e.getMessage());

56e.printStackTrace();

57}

58

59myVideoView.requestFocus();

60//we also set an setOnPreparedListener in order to know when the video file is ready for playback

61myVideoView.setOnPreparedListener(new OnPreparedListener() {

62

63public void onPrepared(MediaPlayer mediaPlayer) {

64// close the progress bar and play the video

65progressDialog.dismiss();

66//if we have a position on savedInstanceState, the video playback should start from here

67myVideoView.seekTo(position);

68if (position == 0) {

69myVideoView.start();

70} else {

71//if we come from a resumed activity, video playback will be paused

72myVideoView.pause();

73}

74}

75});

76

77}

78

79@Override

80public void onSaveInstanceState(Bundle savedInstanceState) {

81super.onSaveInstanceState(savedInstanceState);

82//we use onSaveInstanceState in order to store the video playback position for orientation change

83savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());

84myVideoView.pause();

85}

86

87@Override

88public void onRestoreInstanceState(Bundle savedInstanceState) {

89super.onRestoreInstanceState(savedInstanceState);

90//we use onRestoreInstanceState in order to play the video playback from the stored position

91position = savedInstanceState.getInt("Position");

92myVideoView.seekTo(position);

93}

94}

Lets see in detail the code above.We set theactivity_main.xmllayout and the VideoView: in our Android ActivityAndroidVideoViewExample, 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 addMediaControllerclass by adding the component in the Activity:1if (mediaControls == null) {

2mediaControls = 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 aProgressDialogthat 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();

TipYou 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 anOnPreparedListeneron our VideoView.01myVideoView.setOnPreparedListener(new OnPreparedListener() {

02public void onPrepared(MediaPlayer mediaPlayer) {

03

04// close the progress bar and play the video

05progressDialog.dismiss();

06myVideoView.seekTo(position);

07

08if (position == 0) {

09myVideoView.start();

10} else {

11myVideoView.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()andonRestoreInstanceState().We will useonSaveInstanceState()in order to store the video playback position:1@Override

2public void onSaveInstanceState(Bundle savedInstanceState) {

3super.onSaveInstanceState(savedInstanceState);

4savedInstanceState.putInt("Position", myVideoView.getCurrentPosition());

5myVideoView.pause();

6}

And we will useonRestoreInstanceState()in order to play the video playback from the stored position:1@Override

2public void onRestoreInstanceState(Bundle savedInstanceState) {

3super.onRestoreInstanceState(savedInstanceState);

4position = savedInstanceState.getInt("Position");

5myVideoView.seekTo(position);

6}

4. Android ManifestIn 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.xml01

02

06

07

10

11

15

19

20

21

22

23

24

25

5. Build, compile and runWhen 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 ProjectThis was an example of Android VideoView.DownloadYou can download the full source code of this example here:VideoView.zip