All computer source code presented on this page, unless it includes attribution to another author, is provided by Ed Halley under the Artistic License. Use such code freely and without any expectation of support. I would like to know if you make anything cool with the code, or need questions answered.
python/
    bindings.py
    boards.py
    buzz.py
    caches.py
    cards.py
    constraints.py
    csql.py
    english.py
    getch.py
    getopts.py
    gizmos.py
    goals.py
    improv.py
    interpolations.py
    namespaces.py
    nihongo.py
    nodes.py
    octalplus.py
    patterns.py
    physics.py
    pids.py
    pieces.py
    quizzes.py
    recipes.py
    relays.py
    romaji.py
    ropen.py
    sheets.py
    stores.py
    strokes.py
    subscriptions.py
    svgbuild.py
    testing.py
    things.py
    timing.py
    ucsv.py
    useful.py
    uuid.py
    vectors.py
    weighted.py
java/
    CSVReader.java
    CSVWriter.java
    GlobFilenameFilter.java
    RegexFilenameFilter.java
    StringBufferOutputStream.java
    ThreadSet.java
    Throttle.java
    TracingThread.java
    Utf8ConsoleTest.java
    droid/
        ArrangeViewsTouchListener.java
        DownloadFileTask.java
perl/
    CVQM.pm
    Kana.pm
    Typo.pm
cxx/
    CCache.h
    equalish.cpp
Download DownloadFileTask.java
/*
**********
**
** Copyright (C) 2011 Ed Halley
** http://halley.cc/ed/
**
** Adapted and expanded from a simpler example found on blogspot by 'Sergey':
** http://tinyurl.com/6cxz9ya
**
** This version is for any file type, fixes a couple bugs, recycles its
** byte buffer, allows the user to cancel, and gives the caller code a
** simple callback scheme to perform follow-up work.
** 
**********
*/

package cc.halley.droid;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

/**
 * Downloads from a URL, saving to an internal app-private file.
 * Displays a progress bar and allows the user to cancel the operation.
 * 
 * <code>
 *    DownloadFileTask task = new DownloadFileTask(context)
 *      { public void onSuccess(String filename) { ... } };
 *
 *    task.execute("http://example.com/file/to/download.png");
 * </code>
 */
public class DownloadFileTask
    extends AsyncTask<String,Integer,String>
{
    private ProgressDialog progressDialog;
    private HttpURLConnection connection;
    private InputStream stream;
    private Context context;
    private int downloaded;
    private int size;

    private static final int MAX_BUFFER_SIZE = 1024;

    public DownloadFileTask(Context context)
    {
        size = 0;
        downloaded = 0;
        connection = null;
        this.context = context;
    }

    /**
     * Called in the UI thread before work begins.  We set up a basic
     * progress dialog that will be updated with download percentage progress.
     */
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    /**
     * Called in the async (non-UI) thread for each argument given to the
     * <code>task.execute()</code> method.  We attempt to download from the
     * given URL, saving to the base filename locally.
     */
    @Override
    protected String doInBackground(String... url)
    {
        String filename = null;
        try
        {
            if (!isOnline())
                return null;

            // figure out where to put the file
            URL u = new URL(url[0]);
            String path = u.getPath();
            if (path.endsWith("/"))
                path = path + "index.html";
            filename = new File(path).getName();

            // prepare for reading
            Log.v("DownloadFileTask", "Starting download from URL: " + u);
            connection = (HttpURLConnection)u.openConnection();
            size = connection.getContentLength();
            connection.connect();
            stream = connection.getInputStream();

            // prepare for writing
            // loop for each buffer chunk
            OutputStream out = context.openFileOutput(filename, 0);
            byte buffer[] = new byte[MAX_BUFFER_SIZE];
            while (true)
            {
                int read = stream.read(buffer);
                if (read == -1)
                {
                    publishProgress(100);
                    break;
                }
                out.write(buffer, 0, read);
                downloaded += read;
                publishProgress(downloaded * 100 / size);
            }
            out.close();

            return filename;
        }
        catch (Exception e)
        {
            Log.e("DownloadFileTask", "doInBackground failed", e);
            try { if (filename != null) context.deleteFile(filename); }
            catch (Exception ex) { ; }
            return null;
        }
    }

    /**
     * Called in the UI thread shortly after the background function calls
     * its own <code>publishProgress()</code> method.  We update the progress
     * dialog with the given percentage value.
     */
    @Override
    protected void onProgressUpdate(Integer... changed)
    {
        progressDialog.setProgress(changed[0]);
    }

    /**
     * Called on the UI thread after completion, if the user has canceled
     * the task with a Back button press or other interruption.
     */
    @Override
    protected void onCancelled()
    {
        super.onCancelled();
        onFailure();
    }

    @Override
    protected void onPostExecute(String result)
    {
        progressDialog.dismiss();
        if (result != null)
            onSuccess(result);
        else
            onFailure();
    }

    /**
     * Check if the Android platform thinks that there is a network available.
     * @return true if the system should allow for Internet access
     */
    public boolean isOnline()
    {
        try
        {
            ConnectivityManager cm =
                (ConnectivityManager)context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null)
                return false;
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (info == null)
                return false;
            return info.isConnectedOrConnecting();
        }
        catch (Exception e)
        {
            Log.e("DownloadFileTask", "isOnline failed", e);
            return false;
        }
    }

    /**
     * Optionally override this for custom failure behavior.
     * Default behavior pops up a generic (English) alert dialog message.
     */
    public void onFailure()
    {
        AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Error!");
        alertDialog.setMessage("Could not complete download.");
        alertDialog.show();
    }
    
    /**
     * Override this to perform follow-up tasks after a successful download.
     * @param filename
     */
    public void onSuccess(String filename)
    {
    }
}


Contact Ed Halley by email at ed@halley.cc.
Text, code, layout and artwork are Copyright © 1996-2013 Ed Halley.
Copying in whole or in part, with author attribution, is expressly allowed.
Any references to trademarks are illustrative and are controlled by their respective owners.
Make donations with PayPal - it's fast, free and secure!