Android Async File Download


You want to show a user a PDF using your android app. This should be relatively simple right? Well there are several things to consider. First you need to download the document locally, in the background without disturbing the user.

Android Async File Download Helper

This snippets below manages the download task/thread using the AsyncTask implementation. Once the file download is completed, it saves the file to the storage and communicates the completion to its listeners. Here, I am checking the callback delegate to see if the consume has passed in a concrete OnFileDownloadedFromUrl implementation. I am also sending out a broadcast

Helper Class

public static void DownloadFileFromUrl(Context context, String url, final OnFileDownloadedFromUrl callback)

    class DownloadTask extends AsyncTask<String, Integer, String>
        private PowerManager.WakeLock mWakeLock;
        private Context context;

        public DownloadTask(Context context) {
            this.context = context;

        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();

                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();

                // download the file
                input = connection.getInputStream();
                //File file = new File(((Sirva)context.getApplicationContext()).getFilesDir(), GetFileNameFromUrl(sUrl[0]));

                //f = context.openFileOutput(directory, Context.MODE_WORLD_READABLE);
                output = context.openFileOutput(GetFileNameFromUrl(sUrl[0]), Context.MODE_WORLD_READABLE);

                byte[] buffer = new byte[1024];
                int len = 0;

                while ((len = > 0) {
                    output.write(buffer, 0, len);

                return context.getFileStreamPath(GetFileNameFromUrl(sUrl[0])).getAbsolutePath();

            } catch (Exception e) {
                return null;
            } finally {
                try {
                    if (output != null)
                    if (input != null)
                } catch (IOException ignored) {

                if (connection != null)

        protected void onPreExecute() {
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        protected void onPostExecute(String result) {
            boolean successful = (result != null);
            if(callback != null)

                callback.FileFinishedDownloading(successful, result);
            HashMap<String,String> extras = new HashMap<String, String>();
            extras.put("BROADCAST_EXTRA_FILE_DOWNLOAD_IS_SUCCESSFUL", String.valueOf(successful));
            extras.put("BROADCAST_EXTRA_FILE_DOWNLOAD_URL", result);
            ((MyAppContext) context.getApplicationContext()).SendBroadcast("", extras);


    final DownloadTask downloadTask = new DownloadTask(context);


Interface Definition

public interface OnFileDownloadedFromUrl
    public void FileFinishedDownloading(boolean isSuccessful, String deviceFileUri);



Pass in the context as the first parameter, the url of the file to download and include a delegate class implementing the OnFileDownloadedFromUrl interface.

FileSystemHelper.DownloadFileFromUrl(view.getContext(), url, null);
Posted in Uncategorized.