^

Download Manager Class

Article 52 in Android-Java

2020-09-19 04:36:37 from bugfish
Download Manager Class
Android-Java / Hints
Last Review on: 2021-02-27 03:34:46 | Hits: 159

Here a simple Download Manager Class.

Use like this:

  DownloadManager DM = new DownloadManager();
  DM.init(....);
  DM.execute();

Here the Class:

import android.os.AsyncTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadManager extends AsyncTask<Void, Void, Void> {
    /////////////////////////////////////////////////
    // Needed class Variables
    File apkStorage = null;
    File outputFile = null;
    private String downloadUrl = "", downloadFileName = "";
    String FilePath =   null;
    boolean isValid;
    boolean isExisting;

    /////////////////////////////////////////////////
    // Initialise the Download
    void initDownload(String IntFilePath, String downloadUrl, String filename, boolean checkExistingState)  {
        this.FilePath = IntFilePath;
        this.downloadUrl = downloadUrl;
        this.downloadFileName = filename;
        this.isExisting =   checkExistingState;
    }

    /////////////////////////////////////////////////
    // Check if a Downloaded Process is Valid
    boolean getValidity() {
        return isValid;
    }

    /////////////////////////////////////////////////
    // Rename a Ready File
    private void renameFile(String inputFile) {
        try {
            File tmpFile = new File(this.FilePath , "file.temp");
            if(new File(this.FilePath, inputFile).exists()) {
                if(new File(this.FilePath, inputFile).delete()) {
                    if (!tmpFile.renameTo(new File(this.FilePath, inputFile))) {
                        isValid = false;
                    }

                }
            } else {
                if (!tmpFile.renameTo(new File(this.FilePath, inputFile))) {
                    isValid = false;
                }
            }

        }
        catch (Exception ignored) {
            isValid = false;
        }
    }

    /////////////////////////////////////////////////
    // Background Download
    @Override
    protected Void doInBackground(Void... arg0) {
        try {
            //////////////////////////////
            // Stop if File Exists
            File checkFile = new File(new File(this.FilePath + "/"), downloadFileName);
            if (isExisting) {
                if (checkFile.exists()) {
                    isValid =   true;
                    return null;
                }
            }

            //////////////////////////////
            // Start Download Operations
            URL url = new URL(downloadUrl);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.connect();

            //////////////////////////////
            // Return Null if HTTP Request Misbehave
            if (c.getResponseCode() != HttpURLConnection.HTTP_OK) {
                isValid =   false;
                return null;
            }

            //////////////////////////////
            // Create Files Variable
            apkStorage = new File(this.FilePath + "/");

            //////////////////////////////
            // Create Directory if Needed
            if (!apkStorage.exists()) {
                if(!apkStorage.mkdir()) {
                    isValid = false;
                    return null;
                }
            }

            //////////////////////////////
            // Write Temp Output File
            outputFile = new File(apkStorage, "file.temp");

            //////////////////////////////////////////////////////////////////////////////////////////////////////
            // Start Writing the File and CHeck for Existens of Real File / Reset the File if Overwrite Enabled
            if (!outputFile.exists()) {
                if(!outputFile.createNewFile()) {
                    isValid = false;
                    return null;
                }
            } else {
                ////////////////////////////////
                // Create Empty File
                PrintWriter writer = new PrintWriter(outputFile);
                writer.print("");
                writer.close();
            }

            //////////////////////////////////////////////////////////////////////////////////////////////////////
            // File Operations
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1;
            while ((len1 = is.read(buffer)) != -1) {
                //Write A New File
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

        } catch (Exception e) {
            //////////////////////////////
            // Return Null to Outputfile if Exception Occurs
            outputFile = null;
        }

        try {
            ///// Check if Download Successfull
            isValid = outputFile != null;
        } catch (Exception e) { isValid = false; }

        ///// Move the File to its Final Location if Download Successfull
        if (isValid) { renameFile(downloadFileName); }

        return null;
    }

    /////////////////////////////////////////////////
    // On Post Execute Function
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }

    /////////////////////////////////////////////////
    // On Pre Execute Function
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

}

I do not guarantee the reliability of the information given here, the code described on this page is executed at your own risk and in the event of damage or other unforeseeable consequences I am in no way responsible or liable.
Comment Section
Currently 0 Upvotes!
captcha image

System - 2021-01-01 19:30:08
We appreciate comments on our site!

This Website is using Session Cookies for Site Functionality and AWStats.
Radio