Thursday, 29 March 2012

Download an image using Asynctask with ProgressDialog

/***********************DownloadActivity.java********************/
package com.image.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DownloadActivity extends Activity {
 
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button)findViewById(R.id.startBtn);
        startBtn.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                startDownload();
            }
        });
    }

    private void startDownload() {
        //String url = "http://www.mobilemarketingwatch.com/wordpress/wp-content/uploads/2010/04/Android-Growing-Quickly-App-Growth-Up-70-Percent-60K-Activations-Per-Day-300x300.jpg";
        String url = "http://cache.gawkerassets.com/assets/images/4/2011/11/2caf61af0c8d4d4beba307403e7d44da.jpg";
        new DownloadFileAsync().execute(url);
    }

    public class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
mProgressDialog = new ProgressDialog(DownloadActivity.this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.setMax(100);
mProgressDialog.show();
    }

    @Override
    protected String doInBackground(String... aurl) {
    int count;
   
    try {

           URL url = new URL(aurl[0]);
           Log.d("\nANDRO_ASYNC", "doInBackground.................................. ");
               
                String fileName = DownloadActivity.this.getFilesDir().getAbsolutePath()+"/newPhoto.jpg";    // /data/data/com.image.download/files
           String filePath = Environment.getExternalStorageDirectory() + "/phone.jpg"; // /sdcard

           Log.d("Name ******************** ", ""+ Environment.getExternalStorageDirectory());
                Log.d("\nFILENAME:   ", " "+DownloadActivity.this.getFilesDir().getAbsolutePath());
             
File file = new File(filePath);
                long startTime = System.currentTimeMillis();

                Log.d("\nImageManager", "download url:" + url);
                Log.d("\nImageManager", "downloaded file name:" + filePath);

                URLConnection ucon = url.openConnection();
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                int lenghtOfFile = ucon.getContentLength();
           Log.d("\nANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                byte[] buffer = new byte[1024];
                int len1 = 0;
                long total = 0;
             
                while ((len1 = is.read(buffer)) > 0) {
                    total += len1;
                    publishProgress("" + (int)((total*100)/lenghtOfFile));              
                    baf.append((byte) current);
                }
             
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();

                Log.d("\nImageManager", "download ready in"+ ((System.currentTimeMillis() - startTime) / 1000));

    } catch (Exception e) {
    Log.d("Exception: ", e.getMessage());
    }
    return null;
    }

@Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.incrementProgressBy(Integer.parseInt(progress[0]));
}

    @Override
    protected void onPostExecute(String unused) {
    mProgressDialog.dismiss();
    }
    }
}

/***************************main.xml***************************/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/startBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="start" >
    </Button>

</LinearLayout>

No comments:

Post a Comment