SoFunction
Updated on 2025-04-07

Android simple implementation of file download

This article shares the specific code for Android simple file download for your reference. The specific content is as follows

Permissions

<!--  File read and write permissions  -->
<uses-permission android:name=".READ_EXTERNAL_STORAGE" />
<!--  Access memory  -->
<uses-permission android:name=".WRITE_EXTERNAL_STORAGE" />

DownloadOkHttp Use (no display)

Download completion address: /storage/emulated/0/Xiaohongshu/

().download(apk, () + "/" + "Little Red Book", new () {
    @Override
    public void onDownloadSuccess() {
      ("download","success");
                }

              @Override
                      public void onDownloading(int progress) {
                       ("download", (progress));
                         }

                    @Override
                   public void onDownloadFailed() {
                   ("download","fail");
         }
 });

Download Use (displayed)

Download completed address: /Xiaohongshu/Xiaohongshu.apk

new (this, apk, "Little Red Book.apk", "Little Red Book");

dialog_progress

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/dp_20"
    android:orientation="vertical">

    <ProgressBar
        android:
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <TextView
        android:
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"
        android:gravity="right"
        android:text="0 %"
        android:layout_height="wrap_content"/>

</LinearLayout>

**Tool class DownloadUtil (two implementation methods, understand by yourself!!!)

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;

import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;
import ;

/**
  * Created by: Simon
  * Created on: 2021/6/7 13:58
  * Description: File download
  */

public class DownloadUtil {

    public static class DownloadOkHttp {

        private static DownloadOkHttp downloadUtil;
        private final OkHttpClient okHttpClient;

        public static DownloadOkHttp get() {
            if (downloadUtil == null) {
                downloadUtil = new DownloadOkHttp();
            }
            return downloadUtil;
        }

        private DownloadOkHttp() {
            okHttpClient = new OkHttpClient();
        }

        /**
          *
          * @param url Download connection
          * @param saveDir SDCard directory that stores downloaded files
          * @param listener Download and listen
          */
        public void download( String url, final String saveDir, final OnDownloadListener listener) {
            Request request = new ().url(url).build();
            (request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    // Download failed                    ();
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    // directory to store downloaded files                    String savePath = isExistDir(saveDir);
                    try {
                        is = ().byteStream();
                        long total = ().contentLength();
                        File file = new File(savePath, getNameFromUrl(url));
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = (buf)) != -1) {
                            (buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            // Downloading                            (progress);
                        }
                        ();
                        // Download completed                        ();
                    } catch (Exception e) {
                        ();
                    } finally {
                        try {
                            if (is != null)
                                ();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                ();
                        } catch (IOException e) {
                        }
                    }
                }
            });
        }

        /**
          * Determine whether the download directory exists
          * @param saveDir
          * @return
          * @throws IOException
          */
        private String isExistDir(String saveDir) throws IOException {
            // Download location            File downloadFile = new File((), saveDir);
            if (!()) {
                ();
            }
            String savePath = ();
            return savePath;
        }

        /**
          * url
          * Parses file name from download connection
          */
        @NonNull
        public static String getNameFromUrl(String url) {
            return (("/") + 1);
        }

        public interface OnDownloadListener {
            /**
              * Download successfully
              */
            void onDownloadSuccess();

            /**
              * @param progress
              * Download progress
              */
            void onDownloading(int progress);

            /**
              * Download failed
              */
            void onDownloadFailed();
        }
    }

    public static class Download {

        private String fileSavePath = "";//Local path to save the file        private String fileDownLoad_path = "";//Download URL        private String mfileName = "";//Downloaded file name        private boolean mIsCancel = false;
        private int mProgress;
        private ProgressBar mProgressBar;
        private TextView text;
        private Dialog mDownloadDialog;
        private final Context context;

        private static final int DOWNLOADING = 1;
        private static final int DOWNLOAD_FINISH = 2;

        private Handler mUpdateProgressHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch () {
                    case DOWNLOADING:
                        // Set the progress bar                        (mProgress);
                        ((mProgress));
                        break;
                    case DOWNLOAD_FINISH:
                        // Hide the current download dialog box                        ();
                }
            }
        };

        /**
          * Download initialization
          * @param context context
          * @param fileDownLoad_path The URL to download
          * @param mfileName Downloaded file name
          * @param fileSavePath Local path to save the file
          */
        public Download(Context context, String fileDownLoad_path, String mfileName, String fileSavePath) {
             = context;
            this.fileDownLoad_path = fileDownLoad_path;
             = mfileName;
             = () + "/" + fileSavePath;
            showDownloadDialog();
        }

        /**
          * Show the downloaded dialog box
          */
        protected void showDownloadDialog() {
             builder = new (context);
            ("Download");
            View view = (context).inflate(.dialog_progress, null);
            mProgressBar = (ProgressBar) (.id_progress);
            text = (.id_text);
            (view);

            ("Cancel", new () {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Hide the current dialog box                    ();
                    // Set the download status to Cancel                    mIsCancel = true;
                }
            });

            mDownloadDialog = ();
            ();

            // Download the file            downloadFile();
        }

        /**
          * Download the file
          */
        private void downloadFile() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (().equals(Environment.MEDIA_MOUNTED)) {
                            File dir = new File(fileSavePath);
                            if (!()){
                                ();
                            }
                            // Download the file                            HttpURLConnection conn = (HttpURLConnection) new URL(fileDownLoad_path).openConnection();
                            ();
                            InputStream is = ();
                            int length = ();

                            File apkFile = new File(fileSavePath, mfileName);
                            FileOutputStream fos = new FileOutputStream(apkFile);

                            int count = 0;
                            byte[] buffer = new byte[1024];
                            while (!mIsCancel) {
                                int numread = (buffer);
                                count += numread;
                                // Calculate the current position of the progress bar                                mProgress = (int) (((float) count / length) * 100);
                                // Update progress bar                                (DOWNLOADING);

                                // Download completed                                if (numread &lt; 0) {
                                    (DOWNLOAD_FINISH);
                                    break;
                                }
                                (buffer, 0, numread);
                            }
                            ();
                            ();
                        }
                    } catch (Exception e) {
                        ();
                    }
                }
            }).start();
        }
    }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.