Home / Android / Make your own Video player in android

Make your own Video player in android

This android tutorial is to help you make your own video player in android. This video player will fetch all types of video formats on your android device and list them in listview and you can click on any of the listed video to run the video. This video player is simple to make.

Download Video player for android full package.zip for eclipse:

makevideoplayerinandroid.zip

Here we have three important files:

  1. Playingvideo.Java
  2. VideoHome.Java
  3. VideoInfo.Java

Playingvideo.Java

package com.techmentro.mvp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;
import android.media.MediaPlayer.OnCompletionListener;
public class PlayingVideo extends Activity {
	Button pauseAndResume,playlist; 
	ProgressBar videoProgress;
	ProgressBarUpdater pbarUpdater;
	public boolean playFlag;
	VideoView videoView; 
	int vDuration;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			 setContentView(R.layout.playing);
			 videoView=(VideoView)findViewById(R.id.videoView);

			videoProgress=(ProgressBar)findViewById(R.id.videoProgress);
			pauseAndResume=(Button)findViewById(R.id.btnPauseResume);
			pauseAndResume.setOnClickListener(new PauseAndResumeListener());
			playlist=(Button)findViewById(R.id.btnPlaylist);
			playlist.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Log.i("mvp", "returning to playlist...");
					setResult(0);
					finish();
				}

			});
			Intent intent=getIntent();
			String uri=intent.getStringExtra("uri");
			vDuration=intent.getIntExtra("duration",1000);
			//String title=intent.getStringExtra("title");
			//playing.setText("Currently Playing : "+title);
			Log.i("mvp", "Player Activity Started, obtaining media player...");
			playVideo(uri);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		playFlag=false;
	}

	private class PauseAndResumeListener implements OnClickListener
	{

		@Override
		public void onClick(View v) {
			if (pauseAndResume.getText().equals("Pause"))
			{

				videoView.pause();
				pauseAndResume.setText("Resume");
				Log.i("mvp", "paused.");
			}
			else
			{

				videoView.start();
				pauseAndResume.setText("Pause");
				Log.i("mvp", "resumed.");

			}
		}

	}

	private class ProgressBarUpdater extends Thread
	{
	public ProgressBarUpdater()
	{
		playFlag=true;
		start();
		Log.i("mvp", "Max Duration set to "+vDuration);
		videoProgress.setMax(vDuration);
		Log.i("mvp", "Starting progress bar updater thread...");

	}
	public void run()
	{

		while(playFlag)
		{
		Log.i("mvp", "current position is "+videoView.getCurrentPosition());
		videoProgress.setProgress(videoView.getCurrentPosition());
		try{
			Thread.sleep(1000);
		}catch(Exception e){

			Log.i("mvp", "progress bar updater thread interrupted.");
		}
		}
	}
	}

	private void playVideo(String songUri) {
		Uri uri=Uri.parse(songUri);

		if (videoView.isPlaying() )
			{
			videoView.stopPlayback();
			}

		videoView.setVideoURI(uri);
		videoView.start();
		pbarUpdater=new ProgressBarUpdater();
		videoView.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				playFlag=false;
				Toast.makeText(getApplicationContext(),"Video Completed.", Toast.LENGTH_LONG).show();
			}
		});

		Log.i("mvp", "player started...");
		}

}

VideoHome.Java

package com.techmentro.mvp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Process;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class VideoHome extends Activity {
	ListView videoList;
	ArrayList <VideoInfo> videoDetails;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        videoList=(ListView)findViewById(R.id.videoList);
        TextView header=new TextView(this);
        header.setTextColor(Color.GREEN);
        header.setTextSize(25);
        header.setText("Video Files");
        videoList.addHeaderView(header);
       // Log.i("mvp", "Player App started, initializing video list...");
        initializeList();
        //Log.i("mvp", "List Initialized, select video to play...");
    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
	if (resultCode==1)
	{
		Log.i("mvp", "Terminating app...");
		Process.killProcess(Process.myPid());

	}
}

private void initializeList()
{
	 //
	//.i("mvp", "Fetching MediaStore contents... ");
	 ContentResolver resolver=getContentResolver();
	 String projection[]={MediaStore.Video.Media._ID,MediaStore.Video.Media.DISPLAY_NAME,MediaStore.Video.Media.DURATION};
	 Cursor cursor= resolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
	 /*Cursor cursor= resolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
	 int recCount=cursor.getCount();
	 Log.i("mvp", "No. of Videos Found :" +recCount);
	 int fCount=cursor.getColumnCount();
	 Log.i("mvp", "No. of Columns Found :" +fCount);
	 for(int i=0;i<fCount;i++)
		 Log.i("mvp", "No. of Columns Found :" +cursor.getColumnName(i));

	 while(cursor.moveToNext())
	 {
		StringBuffer b=new StringBuffer();
		 for(int i=0;i<fCount;i++)
		 {

			 b.append(cursor.getString(i)).append("\t");
		 }
		 Log.i("mvp", b.toString());
	 }*/
	 videoDetails=new ArrayList<VideoInfo>();
	 while(cursor.moveToNext())
	 {
		int id=cursor.getInt(0);
		String title=cursor.getString(1);
		int dur=cursor.getInt(2);
		videoDetails.add(new VideoInfo(id,title,dur));

	 }
	 cursor.close();
	 Log.i("mvp", "Content Fetched, displaying on list... ");
	 ArrayAdapter<VideoInfo> adapter=new MyArrayAdapter  (getApplicationContext(),R.layout.videolist,videoDetails);
	 videoList.setAdapter(adapter);
     videoList.setOnItemClickListener(new OnItemClickListener() {

	@Override

		public void onItemClick(AdapterView<?> parent, View clickedView, int index, long id) {
			Log.i("mvp", "Video indexed "+index +" is selected for playing, creating uri...");
			VideoInfo info=videoDetails.get(index-1);
			String uri=MediaStore.Video.Media.EXTERNAL_CONTENT_URI+"/"+info.getId();
			Log.i("mvp", "starting activity to play video...");
			Intent intent=new Intent(getApplicationContext(),PlayingVideo.class);
			intent.putExtra("uri", uri);
			intent.putExtra("title", info.getTitle());
			intent.putExtra("duration",info.getDuration());
			startActivityForResult(intent,1);
		}

});
	 // videoList.setOnItemClickListener(new VideoSelectionListener());
	 Log.i("mvp", "Adapter set, Listener registered... ");
}
private class MyArrayAdapter extends ArrayAdapter<VideoInfo>
{

	int layout;

	public MyArrayAdapter(Context context, int layoutId,
			List<VideoInfo> objects) {
		super(context, layoutId, objects);
		layout=layoutId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		RelativeLayout newView;
		VideoInfo detail= videoDetails.get(position);
		 Log.i("mvp", "Generating view for the list... ");
		if (convertView==null)
		{
			Log.i("mvp", "passed view is null, creating new view... ");
			newView=new RelativeLayout(getContext());
			LayoutInflater  li=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
			li.inflate(layout, newView, true);
			Log.i("mvp", "new view created... ");
		}
		else
		{
			newView=(RelativeLayout)convertView;
			Log.i("mvp", "passed view isn't null... ");

		}
		Log.i("mvp", "setting values to list memebers...");
		TextView title=(TextView)newView.findViewById(R.id.title);
		Log.i("mvp", "setting value of title...");
		title.setText(detail.getTitle());
		Log.i("mvp", "value of title set...");
		TextView duration=(TextView)newView.findViewById(R.id.duration);
		duration.setText(detail.getDisplayDuration());
		Log.i("mvp", "value of duration set...");

		return newView;
	}

}
}

 

VideoInfo.Java

package com.techmentro.mvp;

public class VideoInfo {
private int id;
String title,displayDuration;
int duration;
public int getId() {
	return id;
}

public String getDisplayDuration() {
	return displayDuration;
}

public VideoInfo(int id, String title, int duration) {
	super();
	this.id=id;
	this.title = title;
	this.duration=duration;
	this.displayDuration = durationInSeconds(duration);

}

public String getTitle() {
	return title;
}

public int getDuration() {
	return duration;
}

public String durationInSeconds(int dur)
{
	int min,sec;
	int time=dur/1000;
	min=time/60;
	sec=time%60;
	String minPart=Integer.toString(min);
	if (min<10)
	minPart="0"+Integer.toString(min);
	String secPart=Integer.toString(sec);
	if (sec<10)
		secPart="0"+Integer.toString(sec);
	return minPart+":"+secPart;
}
}

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"
    >
   <ListView android:layout_height="wrap_content" android:id="@+id/videoList" 
       android:layout_width="match_parent"></ListView>

</LinearLayout>

OUTPUT:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Preventing spam * Time limit is exhausted. Please reload the CAPTCHA.