Click here to Skip to main content
15,867,686 members
Articles / Mobile Apps / Android

Downloading multiple files using AsyncTask in Android

Rate me:
Please Sign up or sign in to vote.
4.22/5 (8 votes)
1 Dec 2011Eclipse 61.8K   3.9K   24   2
This article teaches you how to download multiple files using progressBar, Notification, and AsyncTask.

Introduction

This article shows how to download multiple files using progressBar, Notification, and AsyncTask.

Using the code

  1. The first thing to do is check the connection using the isInternetConnectionActive(context) method. If this method return true, then create a notification for showing a message:
  2. Java
    private static final int HELLO_ID = 1;
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
            
        if(isInternetConnectionActive(getApplicationContext())) {
         	showNotification(1);
        }
        else {
        	showNotification(0);
        }
    }
         
    private boolean isInternetConnectionActive(Context context) {
        	NetworkInfo networkInfo = ((ConnectivityManager) context
        	    .getSystemService(Context.CONNECTIVITY_SERVICE))
        	    .getActiveNetworkInfo();
    
      if(networkInfo == null || !networkInfo.isConnected()) {
         return false;
      }
         return true;
    }
        
    private void showNotification(int status){
        	String ns = Context.NOTIFICATION_SERVICE;
       NotificationManager mNotificationManager = 
           (NotificationManager) getSystemService(ns);
    
       int icon = android.R.drawable.ic_media_play;
       CharSequence ticketText = "Connection";
       long when = System.currentTimeMillis();
    
       Notification notification = new Notification(icon, ticketText, when);
    
       Context context = getApplicationContext();
       CharSequence contentTitle = "Internet Connection";
       CharSequence contentText = "";
            
       if(status == 1){
         	contentText = "Internet connected, Are you Update your Application?";
       }
       else{
        	contentText = "Internet disconnected!";
       }
           
       Intent notificationIntent = new Intent(this, NotifyPage.class);
       notificationIntent.addFlags(Notification.FLAG_ONGOING_EVENT);
       PendingIntent contentIntent = 
         PendingIntent.getActivity(this, 0, notificationIntent, 0);
    
       notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    
       mNotificationManager.notify(HELLO_ID, notification);
    }
  3. In the showNotification() method, we define an Intent, declare its second parameter as NotifyPage.class. When the user selects a notification, call the activity NotifyPage. For this activity, design an XML file that includes two buttons: a button that creates another notification for showing a progressBar() and a button to cancel download operations and come back home.
  4. Java
    public void clearNotification(View v) {
    		mNotificationManager.cancel(1);
        finish();
    }
    	
    public void UpdateApplication(View v){
    	mNotificationManager.cancel(1);
    	new DownloadTask(this).execute("http://animal.discovery.com/" + 
    	    "birds/peacock/pictures/peacock-picture.jpg");
    }
  5. In the DownloadTask class, you can send several files but in this example, we just send a file address. In fact, with execute(url), you call doInBackground() that runs downloading operations in the background. You can download notification calling using four methods in the DownloadTask class:
  6. Java
    public  DownloadTask(Context context){
       this.context = context;
       //Create the notification object from NotificationHelper class
       mNotificationHelper = new NotificationHelper(context);
    }
    
    protected void onPreExecute(){
       //Create the notification in the statusbar
       mNotificationHelper.createNotification();
    }
    
    protected void onProgressUpdate(Integer... progress) {
       //This method runs on the UI thread, it receives progress updates
       //from the background thread and publishes them to the status bar
       mNotificationHelper.progressUpdate(progress[0]);
    }
    protected void onPostExecute(Void result)    {
       //The task is complete, tell the status bar about it
       mNotificationHelper.completed();
    }

Remember to define permissions related to connection in AndroidManifest.xml: android.permission.INTERNET - android.permission.ACCESS_NETWORK_STATE.

Points of Interest

This article hopefully taught you how to create a status bar notification and use a AsyncTask class for downloading or uploading files.

License

This article, along with any associated source code and files, is licensed under The Eclipse Public License 1.0


Written By
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
davidlow7015-Jan-12 13:05
davidlow7015-Jan-12 13:05 
QuestionSomething's amiss Pin
David Crow8-Dec-11 9:36
David Crow8-Dec-11 9:36 
You wrote, "This article hopefully taught you how to...use a AsyncTask class." No such usage was presented. Was this intentional?

Also, where does the article show multiple files being downloaded?"

"One man's wage rise is another man's price increase." - Harold Wilson

"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

"Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.