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 .


My Prime Minister application

India is going mobile. Every month, more than 6 million people are accessing the Internet for the very first time, through their mobile device. The phone is your window to the outside world, and soon your phone could be your window to the Prime Minister’s Office.


We share Prime Minister Narendra Modi’s vision of innovation, aspiration and connectivity. That’s why we’re so happy to be supporting MyGov in a first of a kind competition as part of the Digital India program to create an app for the Prime Minister’s Office, which PM Modi announced over the weekend:

Rather than tell people what app they should use to engage with the government, the competition will give people a chance to say what they want from an app and India’s immensely talented developers an opportunity to build it. And we’ll provide some guidance and mentoring along the way.

The contest - more info here - will start rolling out now through three phases:
  1. Starting right now and running through March 12th, anyone with an idea on what features an app from the Prime Minister’s Office should include can share it, and vote on other people’s ideas, on www.mygov.in(you’ll need to create an account to get started)
  2. Once all the ideas are in, teams of developers will then be invited to submit rough blueprints (wireframes) for how they would build an app for the Prime Minister’s Office
  3. The five developer teams with the best mockups will be invited to build their ideas with mentorship from Google. The winning app, chosen by an independent jury, will become the official app of the PMO.
    The successful team will also get to visit Google’s US headquarters. Meanwhile, individuals deemed to have submitted the best app ideas will win an Android One device.

india.giv.in-(649x290).jpgIndia’s move from 300 to 500 million people online will reshape everything, including the government-citizen relationship. Already 50 per cent of India’s Internet users are mobile only. No country has built their Internet on that computing platform, in those numbers, at such a pace. In a time of such rapid, exhilarating change, no one person can claim to know the best tools the government can offer it’s citizens. But, as a group, we probably do know the answer. That’s the insight that lies behind democracy in the first place.