How do I download a specific file from the FirebaseStorage using its downloadURL?
I load the image, pdf, and text file into a RecyclerView. When I tap on a CardView (in the RecyclerView) I will be redirected to the file's corresponding download url in a browser. How should I do it so that instead of opening it in a web browser, the file would be downloaded to a specific folder in the user's phone.
Any help is appreciated. Thanks!
CodePudding user response:
To download any file from Url you can simply use the Download Manager of Android this is code to download file from URL
String[] PERMISSIONS = {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
android.Manifest.permission.READ_EXTERNAL_STORAGE,
};
if (!hasPermissions(activity.this, PERMISSIONS)) {
String url = "https://firebasestorage.googleapis.com/v0/b/smart-edubox-90c5d.appspot.com/o/uploaded_files/pdf_files/08-11-2022_15:43:02_dummy.pdf?alt=media&token=f68e7403-0cb7-4c86-9799-1c47fffd9cb5";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
this is permission for Storage
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
and your manifest permissions will be
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />