Skip to main content

Download any file from URL and save in storage with loader in notification


👉 AndroidManifest.xml :

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


👉 DownloadSingleTask :

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.evoli.sanghvi.sanghvi.R;
import com.evoli.sanghvi.sanghvi.common.ServerSettings;
import com.evoli.sanghvi.sanghvi.interfaces.AsyncResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;

public class DownloadSingleTask {

   private static final String TAG = "Download Task";
   public AsyncResponse delegate = null;
   private Context context;
   private String downloadUrl;

   public DownloadSingleTask(AsyncResponse asyncResponse, Context context, String downloadUrl) {
       this.context = context;
       this.downloadUrl = ServerSettings.Main_URL + downloadUrl;
       delegate = asyncResponse;

       //Start Downloading Task
       new DownloadSingleTask.DownloadingTask().execute();
   }

   private class DownloadingTask extends AsyncTask<String, Integer, Void> {

       private int PROGRESS_MAX = 100;
       private int PROGRESS_CURRENT = 0;
       private NotificationManager mNotificationManager;
       private NotificationCompat.Builder mBuilder;
       private int notificationID_;
       private File apkStorage = null;
       private File outputFile = null;

       @Override
       protected void onPreExecute() {
           super.onPreExecute();

           notificationID_ = Application_shangvi.NotificationID.getID();
           mBuilder = new NotificationCompat.Builder(context, "notify_001");

           mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
           mBuilder.setContentTitle(context.getResources().getString(R.string.downloadInProgress));
           mBuilder.setPriority(Notification.PRIORITY_MAX);
           mBuilder.setColor(context.getResources().getColor(R.color.colorLogo));
           mBuilder.setOnlyAlertOnce(true);
           mBuilder.setProgress(0, 0, true);
           mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
               NotificationChannel channel = new NotificationChannel("notify_001", "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
               mNotificationManager.createNotificationChannel(channel);
           }

       }

       @Override
       protected void onPostExecute(Void result) {
           try {
               mBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
               if (outputFile != null) {
                   new Handler().postDelayed(new Runnable() {
                       @Override
                       public void run() {

                           mBuilder.setContentTitle(context.getResources().getString(R.string.downloadCompleted));
                           mBuilder.setProgress(0, 0, false);
                           mNotificationManager.notify(notificationID_, mBuilder.build());
                       }
                   }, 2000);
               } else {
                   new Handler().postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
                           mBuilder.setProgress(0, 0, false);
                           mNotificationManager.notify(notificationID_, mBuilder.build());
                       }
                   }, 2000);
                   Log.e(TAG, "Download Failed");
               }
           } catch (Exception e) {
               e.printStackTrace();
               //Change button text if exception occurs
               new Handler().postDelayed(new Runnable() {
                   @Override
                   public void run() {
                       mBuilder.setContentTitle(context.getResources().getString(R.string.downloadAgain));
                       mBuilder.setProgress(0, 0, false);
                       mNotificationManager.notify(notificationID_, mBuilder.build());
                   }
               }, 2000);
               Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
           }

           try {
               delegate.processFinish(true);
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
           super.onPostExecute(result);
       }

       protected void onProgressUpdate(Integer... progress) {

           mBuilder.setProgress(PROGRESS_MAX, progress[0], true);
           // Displays the progress bar on notification
           mNotificationManager.notify(notificationID_, mBuilder.build());
       }

       @Override
       protected Void doInBackground(String... params) {
           try {

               Calendar calendar = Calendar.getInstance();
               String date = fromInt(calendar.get(Calendar.MONTH))
                       + fromInt(calendar.get(Calendar.DAY_OF_MONTH))
                       + fromInt(calendar.get(Calendar.YEAR))
                       + fromInt(calendar.get(Calendar.HOUR_OF_DAY))
                       + fromInt(calendar.get(Calendar.MINUTE))
                       + fromInt(calendar.get(Calendar.SECOND));


               String[] subFileName = downloadUrl.split("/");
               String downloadFileName = date.toString() + subFileName[subFileName.length - 1];
               Log.e(TAG, downloadUrl);
               Log.e(TAG, downloadFileName);

               URL url = new URL(downloadUrl);//Create Download URl
               HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();//Open Url Connection
               httpURLConnection.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
               httpURLConnection.connect();//connect the URL Connection

               //If Connection response is not OK then show Logs
               if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                   Log.e(TAG, "Server returned HTTP " + httpURLConnection.getResponseCode()
                           + " " + httpURLConnection.getResponseMessage());
               }

               //Get File if SD card is present
               if (new CheckForSDCard().isSDCardPresent()) {
                   apkStorage = new File(Environment.getExternalStorageDirectory(), "/" + context.getResources().getString(R.string.app_name));
               } else
                   Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();

               //If File is not present create directory
               if (!apkStorage.exists()) {
                   apkStorage.mkdir();
                   Log.e(TAG, "Directory Created.");
               }

               outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File

               //Create New File if not present
               if (!outputFile.exists()) {
                   outputFile.createNewFile();
                   Log.e(TAG, "File Created");
               }

               FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location

               InputStream is = httpURLConnection.getInputStream();//Get InputStream for connection

               byte[] buffer = new byte[1024];//Set buffer type
               int len1 = 0;//init length
               while ((len1 = is.read(buffer)) != -1) {
                   fos.write(buffer, 0, len1);//Write new file
                   publishProgress(Math.min(PROGRESS_CURRENT * 10, 100));
                   PROGRESS_CURRENT++;
               }
               //Close all connection after doing task
               fos.close();
               is.close();
               scanPhoto(context, outputFile.toString());

           } catch (Exception e) {
               //Read exception if something went wrong
               e.printStackTrace();
               outputFile = null;
               Log.e(TAG, "Download Error Exception " + e.getMessage());
           }
           return null;
       }
   }

public static String fromInt(int val) {
   return String.valueOf(val);
}

public static void scanPhoto(Context context, String imageFileName) {
   Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
   File f = new File(imageFileName);
   Uri contentUri = Uri.fromFile(f);
   mediaScanIntent.setData(contentUri);
   context.sendBroadcast(mediaScanIntent);
}
}

👉 Call this class :

ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected()) {

       new DownloadSingleTask(new AsyncResponse() {
           @Override
           public void processFinish(Object output) throws UnsupportedEncodingException {

           }
       }, this, url);

} else {
   Toast.makeText(Activity_Main.this, getResources().getString(R.string.NoInternet), Toast.LENGTH_LONG).show();
}


👉 strings.xml :

<string name="NoInternet">No Internet connection</string>


Comments

Popular posts from this blog

Transparent Color Code

Transparent Color Code : Color hexadecimal notation is like the following:  #AARRGGBB A: alpha R: red G: green B: blue ____________________________________________ E.g. for 50% white you'd use             #80FFFFFF.              # ( Transparent  hex value ) (Any Color code) ____________________________________________ Normal opaque black hex- "#000000" Fully transparent - "#00000000" Fully opaque - "#FF000000" 50% transparent - "#80000000" ____________________________________________ Percentages to hex values.  100% — FF 95% — F2 90% — E6 85% — D9 80% — CC 75% — BF 70% — B3 65% — A6 60% — 99 55% — 8C 50% — 80 45% — 73 40% — 66 35% — 59 30% — 4D 25% — 40 20% — 33 15% — 26 10% — 1A 5% — 0D 0% — 00 ____________________________________________ All hex value from 100% to 0% alpha: 100% — FF 99% — FC 98% — FA 97% — F7 96% — F5 95% — F2 94% — F0 93% ...
Dark Theme elevation overlay hex 00dp 0% #121212 01dp 5% #1e1e1e 02dp 7% #222222 03dp 8% #242424 04dp 9% #272727 06dp 11% #2c2c2c 08dp 12% #2e2e2e 12dp 14% #333333 16dp 15% #343434 24dp 16% #383838

Custom Fonts

In android, you can define your own custom fonts for the strings in your application. You just need to download the required font, and then place it in assets/fonts folder. Y ou can access it in your java code through Typeface class. - Use  setTypeface()  method TextView textView = (TextView) findViewById(R.id. TextView1 ) ; Typeface custom_font = Typeface. createFromAsset (getAssets() , "fonts/font name.ttf" ) ; textView.setTypeface(custom_font) ;