How to make any file downloader in Android


Many time developer has to download big file from server and for that he/she has to write downloader class .
In that case developer has to save  file in sdcard manually using FileOutputStream   and OutputStreamWriter   and   manage network on/off case .It takes lot of efforts and time . I would suggest to use  DownloadManager  to overcome these efforts.

Download sourcecode .

 Why should we use DownloadManager  service 
-DownloadManager  is simple to use and handle
-It takes only 5 min to configure to your existing code.
-We can download multiple files concurrently.
-Wifi on/off automatically managed no need extra efforts to handle this.
-You can pause , resume and restart file downloading .



@ Use this line of code to download video file.
@ Just manage refrenceId to manage file downloading .
     -refrenceId is a file downloading id ,with this id we can cancel, pause, resume , file path  of downloading file.

  DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        Request request = new Request(
                Uri.parse("http://sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4"));
        //Uri.parse("http://techslides.com/demos/sample-videos/small.mp4"));
        long enqueue = dm.enqueue(request);




1: To implements in Activity just  create file  MainActivity.java  and copy past this .
this will create some error no need to worry just press ctrl+1 (eclipce user )  or alt+enter (android studio user) all error will remove.  to use ActionBarActivity  just add actioncompat lib  sourcecode

import android.support.v7.app.ActionBarActivity;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {
private DownloadManager dm;
private long enqueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Button download =(Button)findViewById(R.id.download);
         Button check =(Button)findViewById(R.id.check);
         download.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
 dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
       Request request = new Request(
               Uri.parse("http://sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4"));
       //Uri.parse("http://techslides.com/demos/sample-videos/small.mp4"));
       enqueue = dm.enqueue(request);
}
});
         check.setOnClickListener(new OnClickListener() {
 
  @Override
  public void onClick(View v) {
  Intent i = new Intent();
         i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
         startActivity(i);
 
  }
  });
         
    }


    @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);
    }
    
}

2: To receive download complete response just create BroadcastReceiver class 

DownloadCompleteOrClickReceive.java

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

public class DownloadCompleteOrClickReceive extends BroadcastReceiver{

@Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
  DownloadManager dm = (DownloadManager)arg0. getSystemService(Activity.DOWNLOAD_SERVICE);
         if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)||DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
             long downloadId = intent.getLongExtra(
                     DownloadManager.EXTRA_DOWNLOAD_ID, 0);
             DownloadManager.Query query = new DownloadManager.Query();
             query.setFilterById(downloadId);
             Cursor c = dm.query(query);
             if (c.moveToFirst()) {
                 int columnIndex = c
                         .getColumnIndex(DownloadManager.COLUMN_STATUS);
                 if (DownloadManager.STATUS_SUCCESSFUL == c
                         .getInt(columnIndex)) {
                 
                     String uriString = c
                             .getString(c
                                     .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                 }else   if (DownloadManager.STATUS_RUNNING == c
                         .getInt(columnIndex)) {
                Intent i = new Intent();
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
                arg0.startActivity(i);
                 
                 }
             }
         }
}


}



3: Add permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" />


4: register BroadcastReceiver to AndroidManifest.xml and add
IntentFilter   "android.intent.action.DOWNLOAD_COMPLETE" and
"android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"
like below  in  <receiver > tag .


 <receiver android:name="com.example.downloadmangerexample.DownloadCompleteOrClickReceive">
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"></action>

            </intent-filter></receiver>


5: How AndroidManifest.xml looks after writing download all required fields .

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadmangerexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="com.example.downloadmangerexample.DownloadCompleteOrClickReceive">
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"></action>
            </intent-filter></receiver>
    </application>

</manifest>


6: To use styles.xml to your project value folder to use ActionCompat library.



<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>


Download sourcecode .


Previous
Next Post »