DownloadImageTask.java :  » App » trafikkameraandroid » se » peterbjorkman » android » trafikkamera » Android Open Source

Android Open Source » App » trafikkameraandroid 
trafikkameraandroid » se » peterbjorkman » android » trafikkamera » DownloadImageTask.java
// Code from http://progrnotes.blogspot.com/2010/09/c-android.html
// Modified not to be private class of a activity and added some debug logging

package se.peterbjorkman.android.trafikkamera;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Path.FillType;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class DownloadImageTask extends AsyncTask<String, Integer, DownloadImageTask.ResultData> {
  public static final String LOGTAG = DownloadImageTask.class.getName();
  private Context mContext;
  private Drawable d;
  private HttpURLConnection conn;
  private InputStream stream; // to read
  private ByteArrayOutputStream out; // to write

  private double fileSize;
  private double downloaded; // number of bytes downloaded
  private int status = DOWNLOADING; // status of current process
  private ImageView mImageView;
  private TextView mModifiedTimeView;

  private ProgressDialog progressDialog;

  private static final int MAX_BUFFER_SIZE = 1024; // 1kb
  public static final int DOWNLOADING = 0;
  public static final int COMPLETE = 1;

  public DownloadImageTask(Context context, ImageView imageView, TextView modifedDateView) {
    d = null;
    conn = null;
    fileSize = 0;
    downloaded = 0;
    status = DOWNLOADING;
    mContext = context;
    mImageView = imageView;
    mModifiedTimeView = modifedDateView;
  }

  public boolean isOnline() {
    try {
      ConnectivityManager cm = (ConnectivityManager) mContext
          .getSystemService(Context.CONNECTIVITY_SERVICE);
      return cm.getActiveNetworkInfo().isConnectedOrConnecting();
    } catch (Exception e) {
      return false;
    }
  }

  @Override
  protected ResultData doInBackground(String... url) {
    Log.v(LOGTAG, "doInBackground");
    try {
      if ( /*isOnline() == */true) {  // TODO Check online
        Log.v(LOGTAG, "Starting loading image by URL: " + url[0]);
        conn = (HttpURLConnection) new URL(url[0]).openConnection();
        Log.v(LOGTAG, "connection opened: ");
        fileSize = conn.getContentLength();
        if (fileSize < 0){
          Log.w(LOGTAG, "No contentlength recieved from url: " + url[0]);
          out = new ByteArrayOutputStream();
        } else {
          Log.v(LOGTAG, "contentlength recieved: " + fileSize);
          out = new ByteArrayOutputStream((int) fileSize);  
        }
        
        conn.connect();

        int statusCode = conn.getResponseCode();
        Log.v(LOGTAG, "statuscode: " + statusCode);
        // Make sure response code is in the 200 range.
        if (statusCode / 100 != 2) {
          Log.e(LOGTAG, "statuscode: " + statusCode);
          return null; // TODO Exception with message
        }

        stream = conn.getInputStream();
        // loop with step 1kb
        while (status == DOWNLOADING) {
          byte buffer[];

          int bufferSize;
          if (fileSize < 0 || fileSize - downloaded > MAX_BUFFER_SIZE) {
            bufferSize = MAX_BUFFER_SIZE;
          } else {
            bufferSize = (int) (fileSize - downloaded);
          }

          buffer = new byte[bufferSize];

          Log.v(LOGTAG, "Reading " +  bufferSize + " more bytes");
          int read = stream.read(buffer);

          if (read == -1) {
            Log.v(LOGTAG, "Completed");
            publishProgress(100);
            break;
          }
          // writing to buffer
          out.write(buffer, 0, read);
          downloaded += read;
          if (fileSize > 0){
            // update progress bar
            int progess = (int) ((downloaded / fileSize) * 100);
            Log.v(LOGTAG, "Progress: " + progess);
            publishProgress(progess);
          }
        }

        long lastModified = conn.getLastModified();
        Date test = new Date(lastModified);
        if (status == DOWNLOADING) {
          status = COMPLETE;
        }
        Log.v(LOGTAG, "Createing drawable");
        d = Drawable.createFromStream(
            (InputStream) new ByteArrayInputStream(out
                .toByteArray()), "filename");

        Log.v(LOGTAG, "Drawable created");
        ResultData data = new ResultData();
        data.drawable = d;
        data.modifiedDate = test;
        return data;

      }
      else {
        return null;
      }
    } catch (Exception e) {
      ResultData data = new ResultData();
      data.drawable = null;
      data.errorMessage = "Fel vid nedladdning av " + url[0] + "\n" + e.getLocalizedMessage();
      return data;
    }
  }

  @Override
  protected void onProgressUpdate(Integer... changed) {
    Log.v(LOGTAG, "We are making progress.");
    progressDialog.setProgress(changed[0]);
  }

  @Override
  protected void onPreExecute() {
    Log.v(LOGTAG, "onPreExecute.");
    progressDialog = new ProgressDialog(mContext);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(false);
    progressDialog.show();
  }

  @Override
  protected void onPostExecute(ResultData result) {
    if (result.drawable != null) {
      progressDialog.dismiss();
      mImageView.setImageDrawable(result.drawable);
      mModifiedTimeView.setText(result.modifiedDate.toLocaleString());
    } else {
      progressDialog.dismiss();
      AlertDialog alertDialog;
      alertDialog = new AlertDialog.Builder(mContext).create();
      alertDialog.setTitle("Fel");
      alertDialog.setMessage(result.errorMessage);
      alertDialog.setButton("Close",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dlg, int sum) {
              // do nothing, close
            }
          });
      alertDialog.show();
    }
  }
  
  class ResultData{
    public Drawable drawable;
    public Date modifiedDate;
    public String errorMessage;
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.