Delete a downloaded file android - android

So i have used DownloadManager to download a file from the internet using the following code :
public void DownloadFile()
{
Log.d("DownloadFileEntered", "true");
try {
String url = "https://firebasestorage.googleapis.com/v0/b/roti-bank-testing.appspot.com/o/SocialGallery%2Fsome.jpg?alt=media&token=d2ddd40f-0c04-441c-82b1-585fd8743b19";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "somegif.gif");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long d = manager.enqueue(request);
}catch (Exception e)
{
Log.d("DownloadFileEntered", "Error."+e.toString());
}
}
Now say, i want to delete this file.
So to do that, i used the following code :
File file = new File("file://" + Environment.DIRECTORY_DOWNLOADS + "/somegif.gif");
boolean d = file.delete();
Log.d("DownloadFileEntered", "D : "+d);
But apparently, the last Log.d gives the output as false, and the file is also not deleted. So, what is the correct way to delete a file from the external storage?
Also, can we run a function when the download is completed ? if yes then how ?

Hope this will help you:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/somegif.gif");
boolean d = file.delete();
Log.d("DownloadFileEntered", "D : "+d);
And don't forget to set this permission in your manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Related

How to save files with DownloadManager in private path?

I have downloaded some files with DownloadManager, I want to save them where that no one can access them, I mean they are private, just my application can access them and I want after uninstall my app they get deleted. but according to my search DownloadManager can save files just in SDCard that everyone can see my files.
can anyone tell me what to do?
You should probably use:
request.setDestinationInExternalFilesDir(context, DIRECTORY_DOWNLOADS, File.separator + folderName + File.separator + fileName);
Where request is your DownloadManager.Request
This folder (sdcard/Android/data/your.app.package) is accessible to the user, but not visible in galleries (not scanned by media scanner), it's only accessible using file manager. Also, this folder will be deleted when your app gets deleted.
You can use internal storage path to save data internally and it will get deleted when your app will get uninstalled
String dir = getFilesDir().getAbsolutePath();
For Set Your Path For Download File Use: Work For me (Android 11).
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
Complete Code:
First Check Directory
private boolean CreateDirectory() {
boolean ret = false;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getPath() + "/YOUR FOLDER/");
if (!dir.exists()) {
try {
dir.mkdirs();
ret = true;
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
Then:
String URL = " YOUR URL ";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(URL));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("YOUR TITLE");
request.setDescription("YOUR DESCRIPTION");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/YOUR FOLDER/", "YOUR FILE.(mp3|mp4|pdf|...)");
request.setDestinationUri(Uri.fromFile(file));
DownloadManager manager=(DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Long downloadId= manager.enqueue(request);
ok,Finish

Download Manager not working

I'm trying to develop app that show videos and you can Download it
i'm using Download Manager class but it didn't work, also it didn't give me any error :(
this is my download manager code:
public void downloadFileFromUrl(String url, String fileName) {
String filePath=Environment.getExternalStorageDirectory() + File.separator + "BlueNet";
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
try {
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.allowScanningByMediaScanner();
request.setDestinationInExternalPublicDir("/BlueNet/",fileName);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(true);
DownloadManager downloadManager = (DownloadManager)getApplicationContext().getSystemService(DOWNLOAD_SERVICE);
long id= downloadManager.enqueue(request);
Toast.makeText(this, fileName, Toast.LENGTH_LONG).show();
Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
}
catch (Exception ex){
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
}
}
and this is how I'm calling it
downloadFileFromUrl(path, fileName);
where:
path: "192.168.1.5:8080/BlueNet_NMC/blue_elephant.mp4"
filename: "blue_elephant.mp4"
and i already give this permissions to manifests
<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.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so please any help
As I said in the comments, DownloadManager only handles requests starting with http:// or https:// as you can see in the docs.
I don't know exactly what's the problem because I lack information about your server, but I think it's a common issue, so you should avoid using an IP address without providing that scheme.
I had a problem when downloading files with an HTTP URL using the DownloadManger class; but then I did the following and the problem was fixed.
Instead of this code:
String url = "http://masteranime.ir/music/best/Dragon Ball GT Dan Dan Kokoro Hikareteku.mp3";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
use this code:
String url = "http://masteranime.ir/music/best/Dragon Ball GT Dan Dan Kokoro Hikareteku.mp3";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url).replaceAll(" ","%20"));
You have problem in this line - request.setDestinationInExternalPublicDir("/BlueNet/",fileName);
Just remove this line or make directory in another way.
request.setDestinationInExternalPublicDir("/BlueNet/", fileName);
You have to mention directory as first argument here. /BlueNet/ is not a directory.

How to store files generated from app in "Downloads" folder of Android?

I am generating an excelsheet in my app which when generated should be automatically saved in the "Downloads" folder of any android device where all the downloads are typically saved.
I have the following which saves the file under "My Files" folder -
File file = new File(context.getExternalFilesDir(null), fileName);
resulting in -
W/FileUtils﹕ Writing file/storage/emulated/0/Android/data/com.mobileapp/files/temp.xls
I rather want to save the generated file automatically in the "Downloads" folder when the excel sheet is generated.
Update # 1: Please see the snapshot here. What I want is the one circled in red and what you suggested gets stored in the one circled blue (/storage/emulated/0/download) if that makes sense. Please advise on how I can save a file in the one circled red i.e., "Downloads" folder which is different from /storage/emulated/0/Download under "MyFiles"
Use this to get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
And don't forget to set this permission in your manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
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.Request request = new DownloadManager.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 players
DownloadManager manager = (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.
Just use the DownloadManager to download your generated file like this:
File dir = new File("//sdcard//Download//");
File file = new File(dir, fileName);
DownloadManager downloadManager = (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.
I used the following code to get this to work in my Xamarin Droid project with C#:
// Suppose this is your local file
var file = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
var fileName = "myFile.pdf";
// Determine where to save your file
var 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 device
var 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.
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 directory
private fun selectExternalStorageFolder(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 directory
override fun onActivityResult(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 Uri
private fun copyFileToExternalStorage(destination: Uri) {
val yourFile: File = ...
try {
val outputStream = contentResolver.openOutputStream(destination) ?: return
outputStream.write(yourFile.readBytes())
outputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
As Oluwatumbi have answered this question correctly but First you need to check for permission is granted for WRITE_EXTERNAL_STORAGE by following code:
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Request for permission
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}else{
Uri uri = Uri.parse(yourUrl);
DownloadManager.Request request = new DownloadManager.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 players
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
manager.enqueue(request);
}
This is running code download files using DownloadManager for Xamarin android api version 29
public bool DownloadFileByDownloadManager(string imageURL)
{
try
{
string file_ext = Path.GetExtension(imageURL);
string file_name = "MyschoolAttachment_" + DateTime.Now.ToString("yyyy MM dd hh mm ss").Replace(" ", "") + file_ext;
var path = global::Android.OS.Environment.DirectoryDownloads;
Android.Net.Uri uri = Android.Net.Uri.Parse(imageURL);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.SetDestinationInExternalPublicDir(path, file_name);
request.SetTitle(file_name);
request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted); // to notify when download is complete
// Notify the user about the completed "download"
var downloadManager = DownloadManager.FromContext(Android.App.Application.Context);
var d_id = downloadManager.Enqueue(request);
return true;
}
catch (Exception ex)
{
UserDialogs.Instance.Alert("Error in download attachment.", "Error", "OK");
System.Diagnostics.Debug.WriteLine("Error !" + ex.ToString());
return false;
}
}
WORKING ON API 29 AND 30
To get the directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Set this permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add requestLegacyExternalStorage to your application tag in AndroidManifest.xml (for API 29):
<application
...
android:requestLegacyExternalStorage="true">

Android DownloadManager "Impossible to open file"

I'm using DownloadManager to download a file from a webService. The download end successfuly, but when I try to open the new file in the "download" folder I've got this error "Impossible to open file" (and I know I can open this type of file).
Also, when I plug my phone to my computer and when I open the download file with it, the file open successfuly and is not corrupted.
I don't have other error, so I'm really lost !
Here my code:
/*Data*/
int filePosition = position - _subFolderNameList.length;
String url = _folder.getFiles().get(filePosition).getUrl();
String FileName = _folder.getFiles().get(filePosition).getName();
String Description = _folder.getFiles().get(filePosition).getUrl();
/*Prepare request*/
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription(Description);
request.setTitle(FileName);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, FileName);
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request); // Send request
Edit: Permission in the Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Okay I found the problem !
I had to specify the "MIME content type" of the file using setMimeType().
public DownloadManager.Request setMimeType (String mimeType);
Yes you have to specify the MIME type.
Adding a few more details to the accepted answer.
public DownloadManager.Request setMimeType (String mimeType);
To get MIME type you can use the following function.
private String getMimeFromFileName(String fileName) {
MimeTypeMap map = MimeTypeMap.getSingleton();
String ext = MimeTypeMap.getFileExtensionFromUrl(fileName);
return map.getMimeTypeFromExtension(ext);
}
and the following is the Xamarin.Android implementation of the same :
private static string GetMimeTypeFromFileName(string fileName)
{
var map = MimeTypeMap.Singleton;
var ext = MimeTypeMap.GetFileExtensionFromUrl(fileName);
return map.GetMimeTypeFromExtension(ext);
}

DownloadManager - Rename download if file already exists

public void onClick(DialogInterface dialog, int id) {
Uri u = Uri.parse(url);
File f = new File("" + u);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle("");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, f.getName());
// just my bullshit here please correct here
if (f.exists()) {
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,f.getName());
File to = new File(sdcard,"*"+f.getName());
from.renameTo(to);
}
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
I have this little code then when clicked it download file from a url but when the file is already downloaded and have the same name it just show fail, how can I check if file already exist and let the DownloadManager download that file with different name?
The DownloadManager renames files by default when they exist. It will append a -[NUMBER] at the end of the filename.
So hello.jpg is turned to hello-1.jpg.
Maybe have a look at this example. I used it and it works.

Categories

Resources