Download a file to the Android file system, then respond with the file location using the provided Messenger. - Android Network

Android examples for Network:HTTP

Description

Download a file to the Android file system, then respond with the file location using the provided Messenger.

Demo Code


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;

public class Main{
    /**//from  w  w w . j  ava 2s  .  c  om
     * Used for debugging.
     */
    static final String TAG = "DownloadActivity";
    /**
     * The key used to store/retrieve a file's pathname from a Bundle.
     */
    public static final String PATHNAME_KEY = "PATHNAME";
    /**
     * Download a file to the Android file system, then respond with
     * the file location using the provided Messenger. 
     */
    public static void downloadAndRespond(Context context, Uri uri,
            Messenger messenger) {
        sendPath(downloadFile(context, uri), messenger);
    }
    /**
     *   Use the provided Messenger to send a Message to a Handler in
     *   another process.
     *
     *    The provided string, outputPath, should be put into a Bundle
     *    and included with the sent Message.
     */
    public static void sendPath(String outputPath, Messenger messenger) {
        Message msg = Message.obtain();
        Bundle data = new Bundle();
        data.putString(PATHNAME_KEY, outputPath);

        // Make the Bundle the "data" of the Message.
        msg.setData(data);

        try {
            // Send the Message back to the client Activity.
            messenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
    /**
     * Download the file located at the provided internet url using
     * the URL class, store it on the android file system using
     * openFileOutput(), and return the path to the file on disk.
     *
     * @param context   the context in which to write the file
     * @param uri       the web url
     * 
     * @return          the path to the downloaded file on the file system
     */
    public static String downloadFile(Context context, Uri uri) {

        try {
            // Create a temp file.
            final File file = getTemporaryFile(context, uri.toString());
            Log.d(TAG, "    downloading to " + file);

            // Download the contents at the URL, which should
            // reference an image.
            final InputStream in = (InputStream) new URL(uri.toString())
                    .getContent();
            final OutputStream os = new FileOutputStream(file);

            // Copy the contents of the downloaded image to the
            // temp file.
            copy(in, os);
            in.close();
            os.close();

            // Return the pathname of the temp file.
            return file.getAbsolutePath();
        } catch (Exception e) {
            Log.e(TAG, "Exception while downloading. Returning null.");
            Log.e(TAG, e.toString());
            e.printStackTrace();
            return null;
        }
    }
    /**
     * Create a temp file to store the result of a download.
     * 
     * @param context
     * @param url
     * @return
     * @throws java.io.IOException
     */
    static private File getTemporaryFile(final Context context,
            final String url) throws IOException {

        // This is what you'd normally call to get a unique temporary
        // file, but for testing purposes we always name the file the
        // same to avoid filling up student phones with numerous
        // files!
        // return context.getFileStreamPath(Base64.encodeToString(url.getBytes(),
        //                                  Base64.NO_WRAP)
        //                                  + System.currentTimeMillis());

        return context.getFileStreamPath(Base64.encodeToString(
                url.getBytes(), Base64.NO_WRAP));
    }
    /**
     * Copy the contents of an InputStream into an OutputStream.
     * 
     * @param in
     * @param out
     * @return
     * @throws java.io.IOException
     */
    static public int copy(final InputStream in, final OutputStream out)
            throws IOException {
        final int BUFFER_LENGTH = 1024;
        final byte[] buffer = new byte[BUFFER_LENGTH];
        int totalRead = 0;
        int read = 0;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            totalRead += read;
        }

        return totalRead;
    }
}

Related Tutorials