Wednesday, July 27, 2011

Video Streaming On Android

Despite being so simple and easy to develop applications on Android, it's still a tough job to stream a YouTube video. On a requirement of video streaming, I began my search, googled through various sites and blogs but was unsuccessful, and while m writing, i still i don't know the solution. Although I found some solutions.

The first solution that I found for video was, to play the video through the built-in YouTube app or through browser. But this wasn't the desired, as by using this method the control would go to the external app or the browser.
The code for using this approach is here..........

Intent myIntent = new Intent(Intent.ACTION_VIEW);
myIntent.setData(Uri.parse("http://www.youtube.com/watch?v=cxLG2wtE7TM"));
startActivityForResult(myIntent,0);

The other solution was to get the video manually from YouTube and then place it on a Web Server(like Tomcat). This way we could play the video in VideoView by setting the url in one of videoview's method as given here...........

videoView.setMediaController(new MediaController(this));
videoView.setVideoURI(Uri.parse(URL_VIDEO));
videoView.requestFocus();
videoView.start();

This way the video plays like charm, but then i don't know if it's the correct approach or what................

The third option I thought of was, instead of streaming the video every time through HTTP(which indirectly downloads the video and then plays it) I could download the video once and store it on SDcard, later whenever required I could play it through my application. This would save up the cost of network usage and also speed up the video playing except for the time spent at first download. Also it must be noted that if the video being played does not change frequently only then it should be downloaded else not.

This is all I have to say about video streaming in android................
Keeping my search on for Streaming YouTube videos .................

Monday, July 18, 2011

AsynTask, VideoDownload and ProgressBar in Android

In this post I will be dealing about how to download a video in android.........

Downloading a video and simultaneously showing a progressbar in android is elegantly handled by AsyncTask class in Android. AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

The code for video download is as follows.........as can be noted the Downloader class extends AsyncTask.
The Downloader Class has to be nested in your Activity.



public class DownloaderClass extends AsyncTask {

private boolean stop = false;
private FileOutputStream fileOutputStream;
private InputStream inputStream;
// this is the total size of the file
private int totalSize = 0;
// variable to store total downloaded bytes
private int downloadedSize = 0;

private HttpURLConnection urlConnection;
private File videoFile;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
showDialog(0);
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// method

// String
// path=Environment.getExternalStorageDirectory().getAbsolutePath()+PATH+fileName;
try {
// set the download URL, a url that points to a file on the
// internet
// this is the file to be downloaded
System.out.println("doInBackground");

URL url = new URL(params[0]);

// create the new connection
urlConnection = (HttpURLConnection) url.openConnection();

// set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);

// and connect!
urlConnection.connect();

// set the path where we want to save the file
// in this case, going to save it on the root directory of the
// sd card.
// File SDCardRoot = Environment.getExternalStorageDirectory();
String videoPath = SDCARD_ROOT + params[1];
// create a new file, specifying the path, and the filename
// which we want to save the file as.

boolean exists = (new File(videoPath)).exists();
if (!exists) {
new File(videoPath).mkdirs();
}
videoFile = new File(videoPath, VIDEO_NAME);

// this will be used to write the downloaded data into the file
// we
// created
fileOutputStream = new FileOutputStream(videoFile);

// this will be used in reading the data from the internet
inputStream = urlConnection.getInputStream();

// this is the total size of the file
totalSize = urlConnection.getContentLength();

// create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; // used to store a temporary size of the
// buffer

// now, read through the input buffer and write the contents to
// the
// file
while ((bufferLength = inputStream.read(buffer)) > 0 && !stop) {
// add the data in the buffer to the file in the file output
// stream (the file on the sd card
fileOutputStream.write(buffer, 0, bufferLength);
// add up the size so we know how much is downloaded
downloadedSize += bufferLength;
publishProgress((downloadedSize * 100) / totalSize);
// this is where you would do something to report the
// prgress,
// like this maybe
// System.out.println(downloadedSize + "/" + totalSize);

}
// close the output stream when done
fileOutputStream.close();

System.out.println("Downloading finished");

playVideo();
// catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
Log.d("% Downloaded : ", "" + values[0]);
progressDialog.setProgress(values[0]);
}

@Override
protected void onCancelled() {
// TODO Auto-generated method stub

// finish();
System.out.println("onCancelled()");
stop = true;

urlConnection.disconnect();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

videoFile.delete();

}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}}
In your activity call this Downloader class by calling execute() method and pass the videoUrl(from the video is be downloaded) and videoPath(where it is to be stored on SDCard)
as here........
downloaderClassObj.execute(VIDEO_URL, VIDEO_PATH);

That's it your video will start downloading and get stored on the specified location.............so simple isn't it :).

Now lets deal with the progressbar, for this you need to override onCreateDialog() method in your activity..........


@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub

progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Downloading...");
// set the progress to be horizontal
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
progressDialog.setProgress(0);
progressDialog.setMax(100);
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {

public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
downloaderClassObj.cancel(true);
}
});

return progressDialog;
}
From your onPreExecute() method in Downloader class call showDialog() to initiate the progressbar.........the onPreExecute() method gets automatically called as soon as execute() method is called..............

And in the onProgressUpdate() you get the percentage download done...........

onProgressUpdate() gets called, with the function call publishProgress() in the loop while downloading the video............

That's it, your Video Downloading with a progress Bar is accomplished...........

Tuesday, July 12, 2011

What a pitiful situation.......

I am writing this post, just keeping in mind the situation of traffic and pollution in Pune, which I think is really pitiful. Commuting from home to workplace(which is 11km) is now becoming like everyday going on a war. There is terrible traffic on the roads and to add it all people are driving haphazardly.

But what i really feel compassionate about is that people don't have enough public transport facilities. One day while travelling to work place I saw a PMPML bus(the public transport here) in which a school boy was hanging with one hand on the last step of the bus and that too only on a single foot, even a slightest jerk could easily make his hand slip and get him caught under the wheels of the bus.

On the other hand a few men and women(mostly women) are consuming almost 10% of the city's fuel, which I think is quite a lot. More and more women in the city are carelessly opting for cars, and that too less fuel efficient cars as they don't want to compromise with the elegance(of their cars). Without proficient driving they are licensed to use four wheeler, which is constantly adding to the menace. Also no one is aware of the concept of car pooling here or may be they just don't care.

Petrol and diesel prices are sky rocketing but this hardly affects the high income group, they continue to use their luxury cars, leaving the common man to face the brunt of inflation.

It's high time now, and this should be taken seriously...........