Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Steps to download a file in android using Asynctask

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.99k
    Comment on it

    Five Steps for downloading a file using AsyncTask in android

    1. Declare the reference of ProgressDialog class in your Activity globally. Ex:-

      ProgressDialog mProgressDialog;

    2. Instantiate the above reference in onCreate() method of activity. Ex:-

      mProgressDialog = new ProgressDialog(this); // here this is the object of your activity mProgressDialog.setMessage("Please wait");


    3. Create a class MyAsyncTask in same activity.

        private class MyAsyncTask extends AsyncTask {
    
        private Context context;
    
        public MyAsyncTask(Context context) {
            this.context = context;
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }
    
        @Override
        protected String doInBackground(String... sUrl) {
            // take CPU lock to prevent CPU from going off if the user 
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
            wl.acquire();
    
            try {
                InputStream input = null;
                OutputStream output = null;
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(sUrl[0]);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();
    
                    // expect HTTP 200 OK, so we don't mistakenly save error report 
                    // instead of the file
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                         return "Server returned HTTP " + connection.getResponseCode() 
                             + " " + connection.getResponseMessage();
    
                    // this will be useful to display download percentage
                    // might be -1: server did not report the length
                    int fileLength = connection.getContentLength();
    
                    // download the file
                    input = connection.getInputStream();
                    output = new FileOutputStream("/sdcard/file_name.extension");
    
                    byte data[] = new byte[4096];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {
                        // allow canceling with back button
                        if (isCancelled())
                            return null;
                        total += count;
                        // publishing the progress....
                        if (fileLength > 0) // only if total length is known
                            publishProgress((int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }
                } catch (Exception e) {
                    return e.toString();
                } finally {
                    try {
                        if (output != null)
                            output.close();
                        if (input != null)
                            input.close();
                    } 
                    catch (IOException ignored) { }
    
                    if (connection != null)
                        connection.disconnect();
                }
            } finally {
                wl.release();
            }
            return null;
        }
    
        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }
    
        @Override
        protected void onPostExecute(String result) {
            mProgressDialog.dismiss();
            if (result != null)
                Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
        }
    }
    


    4. Call MyAsyncTask class in your onCreate() Method of your Activity.

        MyAsyncTask object = new MyAsyncTask(this);
        object.execute("URL Goes here")
    

    5. Add following permission in your manifest

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: