If you are looking for the code to download the image through the image's url then you are reading the best and simplest blog for the same.
For image downloading I'm using DownloadManager, with the help of DownloadManager I will request to download the particular image by sending the specified url for the image that I wish to download.
![](http://findnerd.s3.amazonaws.com/imagedata/8810/8810.jpg)
So, in the method mentioned below there is one parameter of String type, this parameter is the url for the image that you wish to download, also I'm creating a new directory where the Image will be stored in my device.
public void downloadFile(String url) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/MyApp");
if (direct.exists()) {
if (direct.isDirectory()) {
String[] children = direct.list();
for (int i = 0; i < children.length; i++) {
new File(direct, children[i]).delete();
}
}
}
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Saving Image")
.setDestinationInExternalPublicDir("/MyApp", "myPic.jpg");
mgr.enqueue(request);
//
}
The Directory that will be created by above code will always have one image in it as I'm deleting the child of the directory whenever you will call the method, here is the code snippet that will be deleting the directory if it already exist on your device .
File direct = new File(Environment.getExternalStorageDirectory()+ "/YourApp");
if (direct.exists()) {
if (direct.isDirectory()) {
String[] children = direct.list();
for (int i = 0; i < children.length; i++) {
new File(direct, children[i]).delete();
}
}
}
0 Comment(s)