Android Video download using AsyncTask




Hi,

Today I go to explain how to download any video and save it on device using asynctask.

Here I write a taskhandler class for this one

Create an interface which will handle the result of a downloaded video path from your device.



public interface VideoInterface {
   public void VideoResponse(String response,String filename);
}


Now below code is for the Taskhandle for the video downloading

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.package_name.activities.R;
import com.package_name.VideoInterface;

public class VideoTaskHandler extends AsyncTask<String, String, String> {

Context mcontext;
String urlPaths;
String filename;
VideoInterface objVideoResponse;
boolean isFileExists;
private ProgressDialog progressDialog;
ImageView image;
FileOutputStream outputStream;

public VideoTaskHandler(Context mcontext, VideoInterface objVideoResponse,
String urlPaths, String filename,ImageView image) {
this.mcontext = mcontext;
this.objVideoResponse = objVideoResponse;
this.urlPaths = urlPaths;
this.filename = filename;
this.image = image;
}
public boolean fileExistance(String fname) {
   //File file = new File(mcontext.getFilesDir() + File.separator + "Video/" + fname);
   File cacheDir = getDataFolder(mcontext);
   File cacheFile = new File(cacheDir, fname);
   return cacheFile.exists();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
    DownloadFile(urlPaths, filename);
    return null;
}

private void DownloadFile(String urlPaths, String filename) {
// TODO Auto-generated method stub
try {
     System.err.println("urlPaths for Video:==> "+urlPaths);
     URL wallpaperURL = new URL(urlPaths);
     URLConnection connection = wallpaperURL.openConnection();
     InputStream inputStream = new BufferedInputStream(wallpaperURL.openStream(), 10240);
    File cacheDir = getDataFolder(mcontext);
    File cacheFile = new File(cacheDir, filename);
    FileOutputStream outputStream = new FileOutputStream(cacheFile);
    byte buffer[] = new byte[1024];
    int dataSize;
    int loadedSize = 0;
  while ((dataSize = inputStream.read(buffer)) != -1) {
        loadedSize += dataSize;
          // publishProgress(loadedSize);
        outputStream.write(buffer, 0, dataSize);
   }
  outputStream.close();

} catch (Exception e) {
      e.printStackTrace();
   }
}
public File getDataFolder(Context context) {
    File dataDir = null;
/* Write file to external storage
* if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
dataDir = new File(Environment.getExternalStorageDirectory(), "Video");
if(!dataDir.isDirectory()) {
dataDir.mkdirs();
}
}*/
//Write to internal storage on app path
   if(context.getApplicationInfo().dataDir!=null){
        dataDir = new File(context.getCacheDir(),"App_Viedo");
        if(!dataDir.isDirectory()) {
             dataDir.mkdirs();
        }
}
if(!dataDir.isDirectory()) {
        dataDir = context.getFilesDir();
   }
    return dataDir;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
    progressDialog = ProgressDialog.show(mcontext, null,"Loading...", true);
    progressDialog.setContentView(R.layout.progress_others);
    progressDialog.setCancelable(false);
    TextView hold_msg = (TextView) progressDialog
       .findViewById(R.id.txt_progressmessage);
          hold_msg.setText("Loading...");
//progressDialog.getWindow().setGravity(Gravity.BOTTOM);
      WindowManager.LayoutParams params =   progressDialog.getWindow().getAttributes();
    params.x = 30;
if(filename.equals("HotelVideo.mov")){
     params.y = -500;
}else{
     params.y = 200;
}
//progressDialog.getWindow().setAttributes(params);
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
      isFileExists = fileExistance(filename);
     System.err.println("isFileExists "+isFileExists +" file name "+filename+ " result"+result);
if(isFileExists == true){
   objVideoResponse.VideoResponse("success",filename);
   System.err.println("VideoTaskHandler file save success ");
}else{
    objVideoResponse.VideoResponse("fail",filename,);
     System.err.println("VideoTaskHandler file save fail ");
}
    progressDialog.dismiss();
  }
}



Now Create a MainActivity class

package com.demo.activity;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;


public class MainActivity extends Activity implements OnClickListener,VideoInterface{

Button btn_demo;
VideoView video_demo;
public static String str_Video = "https://static.videezy.com/system/resources/previews/000/001/584/original/Indi anRocksBeachSunset_(12).mp4";
String sample_video = "sample_video.mov";
@Override
protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
       StrictMode.setThreadPolicy(policy);
       setContentView(R.layout.activity_main);
       btn_demo = (Button) findViewById(R.id.btn_demo);
       btn_demo.setOnClickListener(this);
       video_demo = (VideoView) findViewById(R.id.video_demo);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.main, menu);
       return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
            return true;
       }
        return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
      if(v.getId() == R.id.btn_demo){
           new VideoTaskHandler(this, this,str_Video, sample_video).execute();
     }
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
       super.onPause();
        video_demo.stopPlayback();
   }
@Override
protected void onResume() {
        // TODO Auto-generated method stub
          super.onResume();
          video_demo.start();
   }
   @Override
protected void onDestroy() {
        // TODO Auto-generated method stub
          super.onDestroy();
          video_demo = null;
    }

@Override
public void VideoResponse(String response, String filename) {
// TODO Auto-generated method stub
      if (response.equals("success")) {
         boolean filePresent = fileExistance(this, filename);
      if (filePresent == true) {
            String videoFilename = getFilePath(this,
filename);
        video_demo.setVisibility(View.VISIBLE);
        video_demo.setVideoPath(videoFilename);
        video_demo.requestFocus();
    }
  }
}

private String getFilePath(MainActivity mainActivity, String filename) {
// TODO Auto-generated method stub
       File cacheDir = getDataFolder(mainActivity);
       File cacheFile = new File(cacheDir, filename);
       return cacheFile.getAbsolutePath();
  }

private boolean fileExistance(MainActivity mainActivity, String filename) {
// TODO Auto-generated method stub
       File cacheDir = getDataFolder(mainActivity);
       File cacheFile = new File(cacheDir, filename);
       return cacheFile.exists();
}

private File getDataFolder(MainActivity mainActivity) {
// TODO Auto-generated method stub
      File dataDir = null;
      /* Write file to external storage
        * if (Environment.getExternalStorageState().equals(
         Environment.MEDIA_MOUNTED)) {
           dataDir = new File(Environment.getExternalStorageDirectory(),
"Video");
        if (!dataDir.isDirectory()) {
               dataDir.mkdirs();
           }
  }*/

//save file on app path for a device
if(mainActivity.getApplicationInfo().dataDir!=null){
           dataDir = new File(mainActivity.getCacheDir(),"App_Viedo");
           if(!dataDir.isDirectory()) {
               dataDir.mkdirs();
        }
   }
if (!dataDir.isDirectory()) {
        dataDir = mainActivity.getFilesDir();
}

     return dataDir;
   }
}


Xml layout for the MainActivity is as follows

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.demo.activity.MainActivity" >

    <VideoView
        android:id="@+id/video_demo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_above="@+id/btn_demo" />

    <Button
        android:id="@+id/btn_demo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="Start Video" />

</RelativeLayout>



Another way to download video is using an android service class which will download the video in background without affecting on your UI .

For more about video downloading using service class Click Here 


Thanks 
Mahesh Nawale


Comments

Popular posts from this blog

Crypto JS Encryption & Decryption in Android

ListView Over GoogleMapView

Android Interview Material