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
    • 3.00k
    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.

    1. private class MyAsyncTask extends AsyncTask {
    2.  
    3. private Context context;
    4.  
    5. public MyAsyncTask(Context context) {
    6. this.context = context;
    7. }
    8.  
    9. @Override
    10. protected void onPreExecute() {
    11. super.onPreExecute();
    12. mProgressDialog.show();
    13. }
    14.  
    15. @Override
    16. protected String doInBackground(String... sUrl) {
    17. // take CPU lock to prevent CPU from going off if the user
    18. // presses the power button during download
    19. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    20. PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    21. wl.acquire();
    22.  
    23. try {
    24. InputStream input = null;
    25. OutputStream output = null;
    26. HttpURLConnection connection = null;
    27. try {
    28. URL url = new URL(sUrl[0]);
    29. connection = (HttpURLConnection) url.openConnection();
    30. connection.connect();
    31.  
    32. // expect HTTP 200 OK, so we don't mistakenly save error report
    33. // instead of the file
    34. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
    35. return "Server returned HTTP " + connection.getResponseCode()
    36. + " " + connection.getResponseMessage();
    37.  
    38. // this will be useful to display download percentage
    39. // might be -1: server did not report the length
    40. int fileLength = connection.getContentLength();
    41.  
    42. // download the file
    43. input = connection.getInputStream();
    44. output = new FileOutputStream("/sdcard/file_name.extension");
    45.  
    46. byte data[] = new byte[4096];
    47. long total = 0;
    48. int count;
    49. while ((count = input.read(data)) != -1) {
    50. // allow canceling with back button
    51. if (isCancelled())
    52. return null;
    53. total += count;
    54. // publishing the progress....
    55. if (fileLength > 0) // only if total length is known
    56. publishProgress((int) (total * 100 / fileLength));
    57. output.write(data, 0, count);
    58. }
    59. } catch (Exception e) {
    60. return e.toString();
    61. } finally {
    62. try {
    63. if (output != null)
    64. output.close();
    65. if (input != null)
    66. input.close();
    67. }
    68. catch (IOException ignored) { }
    69.  
    70. if (connection != null)
    71. connection.disconnect();
    72. }
    73. } finally {
    74. wl.release();
    75. }
    76. return null;
    77. }
    78.  
    79. @Override
    80. protected void onProgressUpdate(Integer... progress) {
    81. super.onProgressUpdate(progress);
    82. // if we get here, length is known, now set indeterminate to false
    83. mProgressDialog.setIndeterminate(false);
    84. mProgressDialog.setMax(100);
    85. mProgressDialog.setProgress(progress[0]);
    86. }
    87.  
    88. @Override
    89. protected void onPostExecute(String result) {
    90. mProgressDialog.dismiss();
    91. if (result != null)
    92. Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
    93. else
    94. Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
    95. }
    96. }
    97.  


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

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

    5. Add following permission in your manifest

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

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: