Skip to content Skip to sidebar Skip to footer

Download From Firebase Storage + Contentresolver (api >= 29)

I am trying to connect ContentResolver and Firebase Storage downloads. Goal: download the files from Firebase storage either into the image gallery or to audio folder. What I did:

Solution 1:

Eventually I couldn't stick together Uri & File in API >= 29, but here is what worked for me:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                values = newContentValues();
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, af.getFileName());
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures" + customDir);
                values.put(MediaStore.MediaColumns.IS_PENDING, 1);
                AsyncQueryHandlerasyncQueryHandler1=newAsyncQueryHandler(cr){
                    @OverrideprotectedvoidonInsertComplete(int token, Object cookie, Uri uri) {
                        super.onInsertComplete(token, cookie, uri);
                        onUriCreated(uri, af, token, fr);
                    }
                };
                asyncQueryHandler1.startInsert(i, null, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            }

The function:

voidonUriCreated(Uri uri, Attachedfile af, int finalI, FileRepo fr) {
            if(uri != null){
                StorageReference ref = FirebaseStorage.getInstance().getReference(myFireStorageFilePath);

                ref.getDownloadUrl().addOnSuccessListener(newOnSuccessListener<Uri>() {

                    @OverridepublicvoidonSuccess(Uri downloadUri) {
                        RetrieveAndInsert(downloadUri.toString(), uri, finalI, af, fr);
                    }
                }).addOnFailureListener(newOnFailureListener() {
                    @OverridepublicvoidonFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });
             }
        }

and here's where the file gets saved:

publicvoidRetrieveAndInsert(String downloadUri, Uri localUri) {
    newRetrieveTask(localUri).execute(downloadUri);
}
classRetrieveTaskextendsAsyncTask<String, Void, Void> {

    String downloadUri;
    Uri localUri;

    RetrieveTask(Uri localUri) {
        this.localUri = localUri;
    }
    @Overrideprotected Void doInBackground(final String... downloadUri) {

        this.downloadUri = downloadUri[0];
        InputStreaminp=null;
        OutputStreamoutput=null;
        try{
            URLurl=newURL(this.downloadUri);
            URLConnectionurlCon= url.openConnection();
            HttpURLConnectionhttpCon= (HttpURLConnection) urlCon;
            httpCon.connect();
            output = cr.openOutputStream(localUri);
            intlengthOfFile= httpCon.getContentLength();
            inp = newBufferedInputStream(url.openStream(), 8192);// httpCon.getInputStream();byte[] buffer = newbyte[1024];
            int bytesRead;
            longtotal=0;
            while ((bytesRead = inp.read(buffer)) != -1) {
                total += bytesRead;
                output.write(buffer, 0, bytesRead);
            }
            downloadedFiles[0]++;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            cr.delete(localUri, null, null);
        } catch (IOException e) {
            e.printStackTrace();
            cr.delete(localUri, null, null);
        } finally{
            try {
                inp.close();
                output.flush();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e){
                e.printStackTrace();
            }

            ContentValuesvalues=newContentValues();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            cr.update(localUri, values, null, null);
        }

        returnnull;
    }

    @OverrideprotectedvoidonPostExecute(Void result) {
        //
    }
}

Post a Comment for "Download From Firebase Storage + Contentresolver (api >= 29)"