In this blog on Android Download image from URL, you’ll learn:

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

  1. How to download an image from a given URL
  2. Requesting required user permission to write file in Internal Storage

Android Download Image from URL

Android Download Image from URL
Android Download Image from URL

Step 1: Declaring Permission in Android Manifest

First thing to do in your first Android Project is you declare required permissions in your ‘AndroidManifest.xml’ file.

For Android Download Image from URL, we need permission to access the internet to download file and read and write internal storage to save image to internal storage.

Add following lines of code at the top of <application> tag of AndroidManifest.xml file:

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

Step 2: Request required permission from user

Android allows every app to run in a sandbox. If an app needs to access certain resources or information outside that sandbox, it needs to request permission from user.

From Android 6.0 onward, Google wants developers to request permission from user from within the app, for more details on permissions read this.

Therefore for Android Download Image from URL, you’ll need to request Read Storage and Write

For this, we will use the following lines of code to first check if the required permission is already granted by the user, if not then we will request permission for storage read and write permission.

We’re creating a method ‘Downlaod Image’, you can simple call this wherever you need to download the image.

 void DownloadImage(String ImageUrl) {

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
            showToast("Need Permission to access storage for Downloading Image");
        } else {
            showToast("Downloading Image...");
           //Asynctask to create a thread to downlaod image in the background 
            new DownloadsImage().execute(ImageUrl);
        }
    }

Now that we have requested and been granted the user permission, to start with android download image from url, we will create an AsyncTask, as you are not allowed to run a background process in the main thread.

class DownloadsImage extends AsyncTask<String, Void,Void>{

        @Override
        protected Void doInBackground(String... strings) {
            URL url = null;
            try {
                url = new URL(strings[0]);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            Bitmap bm = null;
            try {
                bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }

            //Create Path to save Image
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ "/AndroidDvlpr"); //Creates app specific folder

            if(!path.exists()) {
                path.mkdirs();
            }

            File imageFile = new File(path, String.valueOf(System.currentTimeMillis())+".png"); // Imagename.png
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(imageFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try{
                bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
                out.flush();
                out.close();
                // Tell the media scanner about the new file so that it is
                // immediately available to the user.
                MediaScannerConnection.scanFile(MainActivity.this,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        // Log.i("ExternalStorage", "Scanned " + path + ":");
                        //    Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
            } catch(Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            showToast("Image Saved!");
        }
    }

In the above give lines of code, a URL and Bitmap is created, using BitmapFactory.decodeStream, file is downloaded.

The File path is created to save the image (We have created a folder named ‘AndroidDvlpr’ in DIRECTORY_PICTURES) and download is initialized.

After downloading the file MediaScannerConnection, is called to read metadata from the file and add the file to the media content provider so the image is available for the user.

In the above lines of code, we have also created a method, showToast() to show Toast. complete code here:

 void showToast(String msg){
    Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
    }

Creating an app? Read about Android Rate App feature implementation here to prompt your user to rate your app in the Google Play store here.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like