Monday, January 9, 2012

Event handler of VideoView - OnCompletion, OnPrepared and OnError

Refer to the old exercise "Displays video in VideoView", we can play video on VideoView easily. We can also implement our own event handlers and register with our VideoView using the methods setOnCompletionListener(), setOnPreparedListener() and setOnErrorListener().

Event handler of VideoView

Main code, AndroidVideoViewActivity.java
package com.exercise.AndroidVideoView;

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

public class AndroidVideoViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

VideoView myVideoView = (VideoView)findViewById(R.id.videoview);

String viewSource ="rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQklThqIVp_AsxMYESARFEIJbXYtZ29vZ2xlSARSBWluZGV4YIvJo6nmx9DvSww=/0/0/0/video.3gp";

myVideoView.setVideoURI(Uri.parse(viewSource));
myVideoView.setMediaController(new MediaController(this));

myVideoView.setOnCompletionListener(myVideoViewCompletionListener);
myVideoView.setOnPreparedListener(MyVideoViewPreparedListener);
myVideoView.setOnErrorListener(myVideoViewErrorListener);

myVideoView.requestFocus();
myVideoView.start();
}

MediaPlayer.OnCompletionListener myVideoViewCompletionListener
= new MediaPlayer.OnCompletionListener(){

@Override
public void onCompletion(MediaPlayer arg0) {
Toast.makeText(AndroidVideoViewActivity.this,
"End of Video",
Toast.LENGTH_LONG).show();
}};

MediaPlayer.OnPreparedListener MyVideoViewPreparedListener
= new MediaPlayer.OnPreparedListener(){

@Override
public void onPrepared(MediaPlayer arg0) {
Toast.makeText(AndroidVideoViewActivity.this,
"Media file is loaded and ready to go",
Toast.LENGTH_LONG).show();

}};

MediaPlayer.OnErrorListener myVideoViewErrorListener
= new MediaPlayer.OnErrorListener(){

@Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
Toast.makeText(AndroidVideoViewActivity.this,
"Error!!!",
Toast.LENGTH_LONG).show();
return true;
}};
}


Layout, main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<VideoView
android:id="@+id/videoview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>


Download the files.

No comments:

Post a Comment