Search code examples
androidandroid-asynctaskandroid-broadcastreceiverandroid-download-manager

Download Multiple Images and Change Extension After Downloading


My requirement is to download multiple images in a loop in activity or AsycTask doinBackground method with download manager(I just need to initialize the download but it continue to download images even after app get closed) and store all the images inside sd card within my application folder (eg MyAppFolder) because I need to share image path with another Application and after downloaded I need to change the extension of images so that it is not visible in gallery folder.


Solution

  • public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
    
            String root_sd = Environment.getExternalStorageDirectory().toString();
            // Set the URL to download image 
            String PhotoPictureDownLoadPath= "http://test.com/test.jpg";
            String photoPictureDirectoryPath = root_sd + "/DownloadImages/";
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Call this method in a loop to DOwnLoad Multiple Images.
            new  DownloadImages(MainActivity.this,PhotoPictureDownLoadPath,photoPictureDirectoryPath);
        }
    }
    
    
    
    // Class to download Images
    public class DownloadImages {
        Context myContext;
        String myDownlaodURL;
        String mySdCardSaveImagePath;
    
        public DownloadImages(Context theContext, String theUrl, String thePath) {
            myContext = theContext;
            myDownlaodURL = theUrl;
            mySdCardSaveImagePath = thePath;
    
            String PhotoPictureName = getFilename(myDownlaodURL);
            File PhotoPictureSavePath = new File(mySdCardSaveImagePath + "/" + PhotoPictureName);
            if (PhotoPictureSavePath.exists()) {
                return;
            }
            if (!PhotoPictureSavePath.exists()) {
                download();
            }
        }
    
        public String getFilename(String theFileName) {
    
            String filename = theFileName.substring(theFileName.lastIndexOf("/") + 1, theFileName.length());
            return filename;
        }
    
        public void download() {
            Uri Download_Uri = Uri.parse(myDownlaodURL);
            DownloadManager downloadManager = (DownloadManager) myContext.getSystemService(myContext.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
    
            //Restrict the types of networks over which this download may proceed.
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
            //Set whether this download may proceed over a roaming connection.
            request.setAllowedOverRoaming(true);
            //Set the local destination for the downloaded file to a path within the application's external files directory
            //request.setDestinationInExternalFilesDir(myContext, mySdCardSaveImagePath, split[split.length - 1]);
            //request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES, split[split.length-1]);
    
            String[] split = myDownlaodURL.split("/");
            //Set the local destination for the downloaded file to the folder specified by user.
            File destinationFile = new File(mySdCardSaveImagePath, split[split.length - 1]);
            request.setDestinationUri(Uri.fromFile(destinationFile));
    
            //Set the title of this download, to be displayed in notifications (if enabled).
            request.setTitle(split[split.length - 1]);
            //Set a description of this download, to be displayed in notifications (if enabled)
            request.setDescription(mySdCardSaveImagePath);
    
            request.setVisibleInDownloadsUi(true);
    
            //Enqueue a new download and get the reference Id
            long downloadReference = downloadManager.enqueue(request);
        }
    }
    
    //change the extension of image after downloading
    public class DownloadBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    
                DownloadManager myDownloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
                Cursor c = myDownloadManager.query(new DownloadManager.Query().setFilterById(downloadId));
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c
                            .getInt(columnIndex)) {
    
                        int filenameIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
                        String filename = c.getString(filenameIndex);
    
                        int filePathIndex = c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION);
                        String filePath = c.getString(filePathIndex);
    
    
                        if (!filename.isEmpty()) {
                            int dotposition = filename.lastIndexOf(".");
                            String filename_Without_Ext = filename.substring(0, dotposition);
                            String Ext = filename.substring(dotposition + 1, filename.length());
                            String newFileName = filename_Without_Ext + ".change" + Ext;
                            boolean success = new File(filePath + "/" + filename).
                                    renameTo(new File(filePath + "/" + newFileName));
                            //Log.d("Log", "" + success);
                        }
    
                    }
                }
            }
        }
    }
    
    //use  bellow premissions
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
        <uses-permission android:name="android.permission.INTERNET"/>
    
         <!-- Register Receiver in Manifest-->
         <receiver android:name=".DownloadBroadcastReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
                </intent-filter>
         </receiver>