Android download notification

When you build an application to download a file from the internet, you might want to display download progress on the notification bar to show the user the status of the ongoing operation. To display the progress on the notification bar, you call the setProgess(int max, int progress, boolean indeterminate) of the NotificationCompat.Builder object. The max argument specified the maximum value to be reached at the end of the operation. The progress argument is updated as the operation is ongoing. Typically, it is a "percent complete" value for the operation. In the example application below, the download task is placed in background using AsyncTask class. The progress is updated by calling the publishProgress() method from the doInBackground() method of AsyncTask while the download task is ongoing. The third argument can be true or false. If you can't estimate the length of the operation, the progress bar is indeterminate (true), otherwise it is determinate (false).
Now to have a workable example application on displaying download progress on notification, create a new Android project. Then modify the activity_main.xml file to add one EditText and one Button. The EditText allows the user to enter file url and the button is clicked to download the file.


<LinearLayout 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"
   tools:context="com.example.andexample.MainActivity"
android:background="#111111"
>

   <EditText
     android:id="@+id/txturl"
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:layout_weight="2"
     android:hint="Enter url"
     android:textColor="#44aa77"
     />
   <Button
     android:id="@+id/btdownload"
     android:layout_width="0dp"    
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:text="Download"
     android:onClick="downloadFile"
     />

</LinearLayout>


Here is the MainActivity class. The code is written to perform download task when the user clicks the Download button, generate notification, and display the progress of the download task in the notification bar.

 package com.example.andexample;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {

String storeDir;
Activity context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
storeDir=Environment.getExternalStorageDirectory().toString();
}

public void downloadFile(View view){
EditText et=(EditText)findViewById(R.id.txturl);
String url=et.getText().toString();
if(!url.equals("")){
BackTask bt=new BackTask();
bt.execute(url);
}
else{
Toast.makeText(context, "No input url", Toast.LENGTH_LONG).show();
}

}

// background task to download file
   private class BackTask extends AsyncTask<String,Integer,Void>{  
   NotificationManager mNotifyManager;
   NotificationCompat.Builder mBuilder;  
   protected void onPreExecute(){
       super.onPreExecute();  
       mNotifyManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
          mBuilder = new NotificationCompat.Builder(context);
       mBuilder.setContentTitle("File Download")
       .setContentText("Download in progress")
       .setSmallIcon(R.drawable.ic_launcher);
       Toast.makeText(context, "Downloading the file... The download progress is on notification bar.", Toast.LENGTH_LONG).show();
      
       }
    
       protected Void doInBackground(String...params){
          URL url;
         int count;
try {
url = new URL(params[0]);
String pathl="";
try {   
File f=new File(storeDir);
if(f.exists()){
   HttpURLConnection con=(HttpURLConnection)url.openConnection();
   InputStream is=con.getInputStream();
   String pathr=url.getPath();
   String filename=pathr.substring(pathr.lastIndexOf('/')+1);
   pathl=storeDir+"/"+filename;
   FileOutputStream fos=new FileOutputStream(pathl);
   int lenghtOfFile = con.getContentLength();
   byte data[] = new byte[1024];   
     long total = 0;
     while ((count = is.read(data)) != -1) {
         total += count;
         // publishing the progress
         publishProgress((int)((total*100)/lenghtOfFile));  
         // writing data to output file
         fos.write(data, 0, count);
         }
  
   is.close();
   fos.flush();
   fos.close();
     }
   else{
   Log.e("Error","Not found: "+storeDir);
  
   }

} catch (Exception e) {
e.printStackTrace();

}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      
   return null;
      
       }    
      
       protected void onProgressUpdate(Integer... progress) {
          
       mBuilder.setProgress(100, progress[0], false);
           // Displays the progress bar on notification
           mNotifyManager.notify(0, mBuilder.build());
       }
      
       protected void onPostExecute(Void result){
       mBuilder.setContentText("Download complete");
       // Removes the progress bar
       mBuilder.setProgress(0,0,false);
           mNotifyManager.notify(0, mBuilder.build());
       }    
      
      }

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


Android-download-notification

Posted by: Dara | post date: 10-11-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.