Advertisement
Mr_Krabs

Untitled

Jul 24th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.69 KB | None | 0 0
  1. package com.codeplayon.pdf.download.example;
  2. import android.app.ProgressDialog;
  3. import android.content.Context;
  4. import android.os.AsyncTask;
  5. import android.os.Environment;
  6. import android.os.Handler;
  7. import android.util.Log;
  8. import android.widget.Toast;
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.InputStream;
  12. import java.net.HttpURLConnection;
  13. import java.net.URL;
  14.  
  15. public class DownloadTask {
  16.     private static final String TAG = "Download Task";
  17.     private Context context;
  18.  
  19.     private String downloadUrl = "", downloadFileName = "";
  20.     private ProgressDialog progressDialog;
  21.  
  22.     public DownloadTask(Context context, String downloadUrl) {
  23.         this.context = context;
  24.  
  25.         this.downloadUrl = downloadUrl;
  26.  
  27.  
  28.         downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());//Create file name by picking download file name from URL
  29.         Log.e(TAG, downloadFileName);
  30.  
  31.         //Start Downloading Task
  32.         new DownloadingTask().execute();
  33.     }
  34.  
  35.     private class DownloadingTask extends AsyncTask<Void, Void, Void> {
  36.  
  37.         File apkStorage = null;
  38.         File outputFile = null;
  39.  
  40.         @Override
  41.         protected void onPreExecute() {
  42.             super.onPreExecute();
  43.             progressDialog = new ProgressDialog(context);
  44.             progressDialog.setMessage("Downloading...");
  45.             progressDialog.setCancelable(false);
  46.             progressDialog.show();
  47.         }
  48.  
  49.         @Override
  50.         protected void onPostExecute(Void result) {
  51.             try {
  52.                 if (outputFile != null) {
  53.                     progressDialog.dismiss();
  54.                     ContextThemeWrapper ctw = new ContextThemeWrapper( context, R.style.Theme_AlertDialog);
  55.                     final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
  56.                     alertDialogBuilder.setTitle("Document  ");
  57.                     alertDialogBuilder.setMessage("Document Downloaded Successfully ");
  58.                     alertDialogBuilder.setCancelable(false);
  59.                     alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
  60.                         public void onClick(DialogInterface dialog, int id) {
  61.  
  62.                         }
  63.                     });
  64.  
  65.                     alertDialogBuilder.setNegativeButton("Open report",new DialogInterface.OnClickListener() {
  66.                         public void onClick(DialogInterface dialog, int id) {
  67.                             File pdfFile = new File(Environment.getExternalStorageDirectory() + "/CodePlayon/" + downloadFileName);  // -> filename = maven.pdf
  68.                             Uri path = Uri.fromFile(pdfFile);
  69.                             Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
  70.                             pdfIntent.setDataAndType(path, "application/pdf");
  71.                             pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  72.                             try{
  73.                                context.startActivity(pdfIntent);
  74.                             }catch(ActivityNotFoundException e){
  75.                                 Toast.makeText(context, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
  76.                             }
  77.                         }
  78.                     });
  79.                     alertDialogBuilder.show();
  80. //                    Toast.makeText(context, "Document Downloaded Successfully", Toast.LENGTH_SHORT).show();
  81.                 } else {
  82.  
  83.                     new Handler().postDelayed(new Runnable() {
  84.                         @Override
  85.                         public void run() {
  86.  
  87.                         }
  88.                     }, 3000);
  89.  
  90.                     Log.e(TAG, "Download Failed");
  91.  
  92.                 }
  93.             } catch (Exception e) {
  94.                 e.printStackTrace();
  95.  
  96.                 //Change button text if exception occurs
  97.  
  98.                 new Handler().postDelayed(new Runnable() {
  99.                     @Override
  100.                     public void run() {
  101.  
  102.                     }
  103.                 }, 3000);
  104.                 Log.e(TAG, "Download Failed with Exception - " + e.getLocalizedMessage());
  105.  
  106.             }
  107.  
  108.  
  109.             super.onPostExecute(result);
  110.         }
  111.  
  112.         @Override
  113.         protected Void doInBackground(Void... arg0) {
  114.             try {
  115.                 URL url = new URL(downloadUrl);//Create Download URl
  116.                 HttpURLConnection c = (HttpURLConnection) url.openConnection();//Open Url Connection
  117.                 c.setRequestMethod("GET");//Set Request Method to "GET" since we are grtting data
  118.                 c.connect();//connect the URL Connection
  119.  
  120.                 //If Connection response is not OK then show Logs
  121.                 if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
  122.                     Log.e(TAG, "Server returned HTTP " + c.getResponseCode()
  123.                             + " " + c.getResponseMessage());
  124.  
  125.                 }
  126.  
  127.  
  128.                 //Get File if SD card is present
  129.                 if (new CheckForSDCard().isSDCardPresent()) {
  130.  
  131.                     apkStorage = new File(Environment.getExternalStorageDirectory() + "/" + "CodePlayon");
  132.                 } else
  133.                     Toast.makeText(context, "Oops!! There is no SD Card.", Toast.LENGTH_SHORT).show();
  134.  
  135.                 //If File is not present create directory
  136.                 if (!apkStorage.exists()) {
  137.                     apkStorage.mkdir();
  138.                     Log.e(TAG, "Directory Created.");
  139.                 }
  140.  
  141.                 outputFile = new File(apkStorage, downloadFileName);//Create Output file in Main File
  142.  
  143.                 //Create New File if not present
  144.                 if (!outputFile.exists()) {
  145.                     outputFile.createNewFile();
  146.                     Log.e(TAG, "File Created");
  147.                 }
  148.  
  149.                 FileOutputStream fos = new FileOutputStream(outputFile);//Get OutputStream for NewFile Location
  150.  
  151.                 InputStream is = c.getInputStream();//Get InputStream for connection
  152.  
  153.                 byte[] buffer = new byte[1024];//Set buffer type
  154.                 int len1 = 0;//init length
  155.                 while ((len1 = is.read(buffer)) != -1) {
  156.                     fos.write(buffer, 0, len1);//Write new file
  157.                 }
  158.  
  159.                 //Close all connection after doing task
  160.                 fos.close();
  161.                 is.close();
  162.  
  163.             } catch (Exception e) {
  164.  
  165.                 //Read exception if something went wrong
  166.                 e.printStackTrace();
  167.                 outputFile = null;
  168.                 Log.e(TAG, "Download Error Exception " + e.getMessage());
  169.             }
  170.  
  171.             return null;
  172.         }
  173.     }
  174. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement