unable to give a path to DownloadManager - android

i would download with DownloadManager a file in a specific directory. At the beginning of my app, i create (if doesn't exist) a folder:
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
externalStorageWriteable = true;
directory_path = Environment.getExternalStorageDirectory()
+ "/" + context.getResources().getString(R.string.app_name);
directory = new File(directory_path);
if (!directory.exists()) {
directory.mkdirs();
}
}
if i check with a filemanager, folder it's available at /sdcard/folderName but if i print on logcat directory_path variable, i obtain
/storage/emulated/0/folderName
I try to download file by passing destination folder like
Uri destination = Uri.fromFile(new File(directory_path));
request.setDestinationUri(destination);
//request is of type DownloadManager.Request
but when i check where file it's stored, my folder is empty and downloaded file is stored inside /sdcard/Download
Could someone tell me why and how can i solve this issue?

Add .toString()
Environment.getExternalStorageDirectory().toString()

Related

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

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

java.lang.IllegalStateException: Failed to get external storage files directory Android

I want to download file to public dir, it works well when sdcard is avaialble but gives me above error when sdcard is not avaiable. I do checking of sdcard.
I want to save files to DIRECTORY_MUSIC which is public by default. But the line request.setDestinationInExternalFilesDir() gives me above error.
Here is the code so far I have written
File dir = new File(Environment
.DIRECTORY_MUSIC + "/" + DIR_NAME + "/");
if (!dir.exists()) {
// create dir for first time
Log.d(LOG_TAG, "first time created dir");
dir.mkdir();
}
DownloadManager dm = (DownloadManager) v.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri songLink = Uri.parse(streamUrl);
DownloadManager.Request request = new DownloadManager.Request(songLink);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(title)
.setMimeType("audio/mp3")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalFilesDir(v.getContext(), dir.getAbsolutePath(),
File.separator + DIR_NAME + File.separator + title);
dm.enqueue(request);
What changes should I do to save file in that dir
I want to save music file which I am downloading from an url and saving to public music directory so that music player will find that file
My question is how Whatsapp make WhatsApp audio folder and download the whatsapp audios to that dir. For phones with SD card I can do this but I fail when there's no SD card in phone. How it is done ?
To save download file in public directory:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, filename);
This method throws:
Throws
IllegalStateException
If the external storage directory cannot be found or create
So you must check if external storage is writable before use.
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
Also requires permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
More info

Saving file in sd card without extension and access that with extension

I am downloading a pdf file from server and saving it on sd card without extension (for security purpose so that normal user can't open that file from file manager).For e.g.- I am downloading abc.pdf and saving it on sd card with abc on below path
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "files");
And later I want to view that file by adding extension.
So when I am accessing that file from code by using below code then its gives error file does't exist..
String s=Environment.getExternalStorageDirectory() + "/files/" + "abc";
File pdfFile = new File(s+".pdf");
So how can I save file in sd card without extension and later open that file with extension.
Workaround for your problem is to rename your saved pdf file without extension to filename with .pdf extension & after completing/accessing view or read operation on your new pdf extension file again you can rename it to file without extension
Example Usage:
String currentFileName = Environment.getExternalStorageDirectory() + File.separator
+ "files" + File.separator + "abc";
String renamedFilename = currentFileName + ".pdf";
boolean isRenamed = renameFile(currentFileName, renamedFilename);
Log.d("isRenamed: ", "" + isRenamed);
if(isRenamed {
//perform your operation
}
Again rename the file if not in use (here exchange renameFile() parameters):
boolean renameAfterOperation = renameFile(renamedFilename, currentFileName);
Log.d("renameAfterOperation : ", "" + renameAfterOperation );
And here is renameFile(currentFilePath, renamedFilePath):
public boolean renameFile(String currentFilePath, String renamedFilePath){
File currentFile = new File(currentFilePath);
File newFile = new File(renamedFilePath);
boolean isrenamed = currentFile.renameTo(newFile);
return isrenamed;
}
In this way whenever you want to perform operation on saved file first rename it to .pdf & whenever it's not in use, again rename it without extension. Let me know if this works for you..

Creating new file from assets folder, isDirectory() returns false

When I call this :
File directory = new File("file:///android_asset/");
then this :
directory.isDirectory()
Always returns false.
Am I doing something wrong here ?
(Sorry if it is a dumb question)
Edit:
I store several images in the assets folder and I wanted to load them in my app (like an image gallery).
Call
directory.mkdirs();
after you created the File object
Edit:
in your case try to change file url as below:
new File("/mnt/external_sd/");
or find the true path by looking it in eclipse File explorer.. do not start it with file://
May be you are searching for this:
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();

Categories

Resources