AsyncTask and download

September 30, 2012   ·   0 Comments

Screen Shot 2012-09-30 at 10.45.39 AM


package com.powenko.tutorial_system_asynctask_download;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;



public class MainActivity extends Activity { 
    private static final String ImageUrl = "http://www.powenko.com/en/wp-content/uploads/2012/03/IMAG2325-copy.jpg"; 
    private ProgressBar mProgressBar; 
    private ImageView mImageView; 
    private Button mGetImage; 
    private Button mAbort; 
     
    @Override 
    public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.activity_main); 
    mProgressBar = (ProgressBar) findViewById(R.id.async_task_progress); 
    mImageView = (ImageView) findViewById(R.id.async_task_displayer); 
    final ImageLoader loader = new ImageLoader(); 
    mGetImage = (Button) findViewById(R.id.async_task_get_image); 
    mGetImage.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
        loader.execute(ImageUrl); 
        } 
    }); 
    mAbort = (Button) findViewById(R.id.asyc_task_abort); 
    mAbort.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 
        loader.cancel(true); 
        } 
    }); 
    mAbort.setEnabled(false); 
    } 
     
    private class ImageLoader extends AsyncTask<String, Integer, Bitmap> { 
    private static final String TAG = "ImageLoader"; 
 
    @Override 
    protected void onPreExecute() { 
        // Initialize progress and image 
        mGetImage.setEnabled(false); 
        mAbort.setEnabled(true); 
        mProgressBar.setVisibility(View.VISIBLE); 
        mProgressBar.setProgress(0); 
        mImageView.setImageResource(R.drawable.ic_launcher) ; 
    } 
     
    @Override 
    protected Bitmap doInBackground(String... url) { 
        /*
         * Fucking ridiculous thing happened here, to use any Internet connections, either via HttpURLConnection
         * or HttpClient, you must declare INTERNET permission in AndroidManifest.xml. Otherwise you will get
         * "UnknownHostException" when connecting or other tcp/ip/http exceptions rather than "SecurityException"
         * which tells you need to declare INTERNET permission.
         */ 
        try { 
        URL u; 
        HttpURLConnection conn = null; 
        InputStream in = null; 
        OutputStream out = null; 
        final String filename = "local_temp_image"; 
        try { 
            u = new URL(url[0]); 
            conn = (HttpURLConnection) u.openConnection(); 
            conn.setDoInput(true); 
            conn.setDoOutput(false); 
            conn.setConnectTimeout(20 * 1000); 
            in = conn.getInputStream(); 
            out = openFileOutput(filename, Context.MODE_PRIVATE); 
            byte[] buf = new byte[8196]; 
            int seg = 0; 
            final long total = conn.getContentLength(); 
            long current = 0; 
            /*
             * Without checking isCancelled(), the loop continues until reading whole image done, i.e. the progress
             * continues go up to 100. But onPostExecute() will not be called.
             * By checking isCancelled(), we can stop immediately, i.e. progress stops immediately when cancel() is called.
             */ 
            while (!isCancelled() && (seg = in.read(buf)) != -1) { 
            out.write(buf, 0, seg); 
            current += seg; 
            int progress = (int) ((float) current / (float) total * 100f); 
            publishProgress(progress); 
            SystemClock.sleep(1000); 
            } 
        } finally { 
            if (conn != null) { 
            conn.disconnect(); 
            } 
            if (in != null) { 
            in.close(); 
            } 
            if (out != null) { 
            out.close(); 
            } 
        } 
        return BitmapFactory.decodeFile(getFileStreamPath(filename).getAbsolutePath()); 
        } catch (MalformedURLException e) { 
        e.printStackTrace(); 
        } catch (IOException e) { 
        e.printStackTrace(); 
        } 
        return null; 
    } 
     
    @Override 
    protected void onProgressUpdate(Integer... progress) { 
        mProgressBar.setProgress(progress[0]); 
    } 
     
    @Override 
    protected void onPostExecute(Bitmap image) { 
        if (image != null) { 
        mImageView.setImageBitmap(image); 
        } 
        mProgressBar.setProgress(100); 
        mProgressBar.setVisibility(View.GONE); 
        mAbort.setEnabled(false); 
    } 
    } 
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ProgressBar
        android:id="@+id/async_task_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <ImageView
        android:id="@+id/async_task_displayer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/async_task_progress"
        android:src="@drawable/ic_launcher" />

    <Button
        android:id="@+id/async_task_get_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/async_task_displayer"
        android:text="get the Image" />

    <Button
        android:id="@+id/asyc_task_abort"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/async_task_displayer"
        android:text="Stop download" />

</RelativeLayout>

shareShare on FacebookShare on Google+Share on LinkedInEmail this to someonePrint this pageBuffer this pageDigg thisFlattr the authorShare on RedditPin on PinterestShare on StumbleUponShare on TumblrTweet about this on Twitter

By


Readers Comments (0)


You must be logged in to post a comment.

PowenKo’s Online Store

powenko_arduinoBook
Android7

Amazon

adsbygoogle

Recent Posts

Categories

Amazon