-2

I'am developing an android application in which I want to download multiple images from server and store it on SD card. Which is the best approach to perform this task.I want to perform this task in background of application.

Piyush Mulik
  • 9
  • 1
  • 4
  • 3
    it's a very old question you should search before asking Anyway you can find the answer here: http://stackoverflow.com/questions/3296850/how-do-i-transfer-an-image-from-its-url-to-the-sd-card – humazed Mar 27 '16 at 04:53

1 Answers1

4

Use an async task to download and save images to external storage.

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
 * Before starting background thread
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    System.out.println("Starting download");
}

/**
 * Downloading file in background thread
 * */
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        String root = Environment.getExternalStorageDirectory().toString();

        System.out.println("Downloading");
        URL url = new URL(f_url[0]);

        URLConnection conection = url.openConnection();
        conection.connect();
        // getting file length
        int lenghtOfFile = conection.getContentLength();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream to write file

        OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
        byte data[] = new byte[1024];

        long total = 0;
         while ((count = input.read(data)) != -1) {
                total += count;

               // writing data to file
                output.write(data, 0, count);

             }

           // flushing output
            output.flush();

           // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
          Log.e("Error: ", e.getMessage());
        }

        return null;
      }



     /**
     * After completing background task
     * **/
    @Override
    protected void onPostExecute(String file_url) {
      System.out.println("Downloaded");
     }
    }

You just call the above class using

    new DownloadFileFromURL().execute(<The url you want to download from>);

You will also need to add below permissions to Manifest file

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

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

Hope it helps

Ragesh Ramesh
  • 3,470
  • 2
  • 14
  • 20