Search code examples
androidandroid-download-manager

Files downloaded with donwloadManager disappears


I have an app that downloads about 6k photos from a server and store them in a folder configured y my app settings, I keep the files hidden from the gallery with .nomedia file and they are only visible in my app gallery, but when I leave my device charging about 5000 photos disappears, and there are only about 920 left in the folder, I totally don't know why files are being deleted.

here is my download file code

    DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request;
    fileURL = convertUri(fileURL);
    if (!URLUtil.isValidUrl(fileURL)) { return false; }
    Uri downloadUri = Uri.parse(fileURL);
    String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
    deleteFileIfExists( new File( getAbsolutePath(path), fileName ));
    request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI )
            .setTitle(fileName)
            .setAllowedOverRoaming(false)
            .setVisibleInDownloadsUi(false)
            .setDestinationInExternalPublicDir( getPath(path), fileName );
    downloadManager.enqueue(request);

Solution

  • This weekend i tested with 3 different devices and 2 different download methods, in the one with download manager the files dissapeared, so if someone have the same problem here's how I am donwloading the files:

    public static boolean downloadFile(Activity activity, String fileURL) {
        fileURL = convertUri(fileURL);
        if (!URLUtil.isValidUrl(fileURL)) { return false; }
    
        try {
            String fileName = URLUtil.guessFileName(fileURL, null, MimeTypeMap.getFileExtensionFromUrl(fileURL));
            deleteFileIfExists( new File( activity.getExternalFilesDir(""), fileName ));
    
            URL u = new URL(fileURL);
            URLConnection conn = u.openConnection();
            int contentLength = conn.getContentLength();
    
            DataInputStream stream = new DataInputStream(u.openStream());
    
            byte[] buffer = new byte[contentLength];
            stream.readFully(buffer);
            stream.close();
    
            File file = new File(activity.getExternalFilesDir(""), fileName);
            DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
            fos.write(buffer);
            fos.flush();
            fos.close();
        } catch(FileNotFoundException e) {
            return false; // swallow a 404
        } catch (IOException e) {
            return false; // swallow a 404
        }
        return true;
    }