Android Download a File from Internet URL in Java

How to Download a File from URL Link in Android Java Tutorial

This tutorial will guide you to learn how to download a file from web in android java, we will first get a link to an image for downloading it, add required permissions and then pass the download link to the download manager for downloading, we will also set a path for saving the file to a location in the android device.

 


 

First, Create a new android project in Android Studio or use an existing project.

Add these permissions in AndroidManifest.xml

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

 

Next, we need an image to test our download code, let’s try this cat’s image that is hosted in this website.

This is the direct link of the cat’s image

http://www.zidsworld.com/wp-content/uploads/2018/06/cat_1530281469.jpg

 

 

 

 

Open the MainActivity.java, Then add this code, this code should be placed below OnCreate method.

try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES), "myfolder");


if (!imageStorageDir.exists()) {
//noinspection ResultOfMethodCallIgnored
imageStorageDir.mkdirs();
}

// default image extension
String imgExtension = ".jpg";

if (image_uri.toString().contains(".gif"))
imgExtension = ".gif";
else if (image_uri.toString().contains(".png"))
imgExtension = ".png";
else if (image_uri.toString().contains(".3gp"))
imgExtension = ".3gp";

String date = DateFormat.getDateTimeInstance().format(new Date());
String file = getString(R.string.app_name) + "-image-" + date.replace(" ", "").replace(":", "").replace(".", "") + imgExtension;




DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
              Uri downloadUri = Uri.parse("http://www.zidsworld.com/wp-content/uploads/2018/06/cat_1530281469.jpg");
              DownloadManager.Request request = new DownloadManager.Request(downloadUri);

              request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                      .setDestinationInExternalPublicDir(DIRECTORY_PICTURES + File.separator, file)
                      .setTitle(file).setDescription(getString(R.string.save_img))
                      .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

              dm.enqueue(request);

              Toast.makeText(getApplicationContext(), getString(R.string.downloading_img), Toast.LENGTH_LONG).show();


          } catch (IllegalStateException ex) {
              Toast.makeText(getApplicationContext(),"Storage Error", Toast.LENGTH_LONG).show();
              ex.printStackTrace();
          } catch (Exception ex) {
              // just in case, it should never be called anyway
              Toast.makeText(getApplicationContext(),"Unable to save image", Toast.LENGTH_LONG).show();
              ex.printStackTrace();


          }}

 

 

So this is the code for downloading image from a Web link URL to your android device’s pictures directory, the code will be executed as soon as you start the app or the MainActivity.




 

 

Conclusion

  • This code will not cause exceptions because exceptions are caught, so your app will not crash when executing this code
  • If your android device runs on marshmallow, you will need request permission before executing this code.
  • This code is just for test, you can assign this code to a button or to your desired activity.
  • You can try other direct download links to test this code

 

 

, , ,

Post navigation

One thought on “Android Download a File from Internet URL in Java

Leave a Reply

Your email address will not be published. Required fields are marked *

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