yjtgma
Last Updated: February 25, 2016
·
10.02K
· andrepiper
F12d4ff4584670387d78f12f5001e887

Android Async Task with Dialog

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

Read more here http://developer.android.com/reference/android/os/AsyncTask.html

Async task allows for a long task to be processed in the background, thus freeing up the UI thread.

LongTask.java

public class LongTask extends AsyncTask<Void, Void, Boolean>
{
    private Context ctx;
    private String TAG="LongTask.java";
    private String url;
    private ProgressDialog p;
    private String filename;
    private ImageView i;
    private Bitmap bitmap;
    /*
         Constructor
     */
    public LongTask(String fileurl,String filename,ImageView i,Context ctx)
    {
        Log.v(TAG, "Url Passed");
        this.url=fileurl;
        this.ctx=ctx;
        this.filename=filename;
        this.p=new ProgressDialog(ctx);
        this.i=i;
        this.bitmap=null;
    }

    /*
        Runs on the UI thread before doInBackground
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        p.setMessage("Saving image to SD Card");
        p.setIndeterminate(false);
        p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        p.setCancelable(false);
        p.show();
    }

    /*
         This method to perform a computation on a background thread.
     */
    @Override
    protected Boolean doInBackground(Void... voids) {

        /*
            1. Instantiate file class and pass the directory and subdirectory
            SDCARD/PICTURES/Test
        */
        File location = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "Test");

        /*
            2. Create Directory Test with File object media
        */
        if (!location.exists()) {
            if (!location.mkdirs()) {
                Log.v(TAG,"Directory was not created");
                return null;
            }
        }
        /*
            3. Begin HTTP download
         */

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            //check 200 OK for success
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.v("FIle download error", "Error.Status.Code -> " + statusCode +" from url ->"+ url);
                return false;
            }

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    // getting contents from the stream
                    inputStream = entity.getContent();
                    // decoding stream data back into image Bitmap that android understands
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    File thumburl = new File(location, filename+".jpg");
                    try {
                        File file = new File(thumburl.getPath());
                        FileOutputStream fOut = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fOut);
                        fOut.flush();
                        fOut.close();
                        return true;
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    }
                    finally
                    {
                    if (inputStream != null)
                    {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        }
        catch (Exception e) {
            // You Could provide a more explicit error message for IOException
            getRequest.abort();
            Log.e(TAG, "Image download error->"+ e.toString());
        }
        return false;
    }

    /*
        Runs on the UI thread after doInBackground
     */
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        p.dismiss();
        if(result)
        {
            // Do something awesome here
            Toast.makeText(ctx, "Download complete", Toast.LENGTH_SHORT).show();
            i.setImageBitmap(bitmap);
        }
        else
        {
            Toast.makeText(ctx,"Download failed, network issue",Toast.LENGTH_SHORT).show();
        }
    }
}

MyActivty.java

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void GetFile(View view)
    {
        ImageView i=(ImageView)findViewById(R.id.imageView);
        String fileUrl="http://25.media.tumblr.com/d55a509993790027240311c9f611aaf8/tumblr_n0hpzpKEfE1st5lhmo1_1280.jpg";
        LongTask l=new LongTask(fileUrl,"my_large_download_test.jpg",i,MyActivity.this);
        l.execute();

    }
}

Outcome

PicturePicturePicture

Full Source

https://drive.google.com/file/d/0B8MVe8jYOYOSS2oxa09vM01YSk0/edit?usp=sharing

My Setup is IntelliJ 13.0 with Android SDK 19.0 (4.4.2) test on LG Optimus G

This is my first post... enjoy!

Say Thanks
Respond