How To Store Files Generated From App In "downloads" Folder Of Android?
Solution 1:
Use this to get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
And don't forget to set this permission in your manifest.xml:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Solution 2:
Now from your question edit I think understand better what you want.
Files shown on the Downloads menu from the one circled in red are ones that are actually downloaded via the DownloadManager
, though the previos steps I gave you will save files in your downloads folder but they will not show in this menu because they weren't downloaded. However to make this work, you have to initiate a download of your file so it can show here.
Here is an example of how you can start a download:
DownloadManager.Requestrequest=newDownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "fileName");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); // to notify when download is complete
request.allowScanningByMediaScanner();// if you want to be available from media playersDownloadManagermanager= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);
This method is used to download from a Uri and i have not used it with a local file.
If your file is not from the internet you could try saving a temporary copy and get the Uri of the file for this value.
Solution 3:
Just use the DownloadManager to download your generated file like this:
Filedir=newFile("//sdcard//Download//");
Filefile=newFile(dir, fileName);
DownloadManagerdownloadManager= (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
downloadManager.addCompletedDownload(file.getName(), file.getName(), true, "text/plain",file.getAbsolutePath(),file.length(),true);
The "text/plain"
is the mime type you pass so it will know which applications can run the downloadedfile. That did it for me.
Solution 4:
I used the following code to get this to work in my Xamarin Droid project with C#:
// Suppose this is your local filevar file = newbyte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
var fileName = "myFile.pdf";
// Determine where to save your filevar downloadDirectory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
var filePath = Path.Combine(downloadDirectory, fileName);
// Create and save your file to the Android devicevar streamWriter = File.Create(filePath);
streamWriter.Close();
File.WriteAllBytes(filePath, file);
// Notify the user about the completed "download"var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
downloadManager.AddCompletedDownload(fileName, "myDescription", true, "application/pdf", filePath, File.ReadAllBytes(filePath).Length, true);
Now your local file is "downloaded" to your Android device, the user gets a notification, and a reference to the file is being added to the downloads folder. Make sure, though, to ask the user for permission before you write to the file system, otherwise an 'access denied' exception will be thrown.
Solution 5:
For API 29 and above
According to documentation, it is required to use Storage Access Framework
for Other types of shareable content, including downloaded files
.
System file picker should be used to save file to External storage directory.
Copy file to external storage example:
// use system file picker Intent to select destination directoryprivatefunselectExternalStorageFolder(fileName: String) {
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
putExtra(Intent.EXTRA_TITLE, name)
}
startActivityForResult(intent, FILE_PICKER_REQUEST)
}
// receive Uri for selected directoryoverridefunonActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
FILE_PICKER_REQUEST -> data?.data?.let { destinationUri ->
copyFileToExternalStorage(destinationUri)
}
}
}
// use ContentResolver to write file by UriprivatefuncopyFileToExternalStorage(destination: Uri) {
val yourFile: File = ...
try {
val outputStream = contentResolver.openOutputStream(destination) ?: return
outputStream.write(yourFile.readBytes())
outputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
Post a Comment for "How To Store Files Generated From App In "downloads" Folder Of Android?"