I am using download manager to download MP3 Files from my server.
Here is the code for it.
public String createFilePath()
{
String path;
String dir = "APP_NAME";
path = Environment.getExternalStorageDirectory().getPath();
File file = new File(Environment.getExternalStorageDirectory(),dir);
if(!file.exists())
{
file.mkdir();
}
path += "/" +dir + "/";
System.out.println("-- saving path : " + path);
return path;
}
public void startDownload() {
Uri uri=Uri.parse(URLFixer.Fix(DATA.url));
System.out.println("-- download path : " + createFilePath() + FileNameGetter.getFileName(DATA..url));
DownloadManager.Request request = new Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle(DATA..title);
request.setDescription(DATA.artist + " - " + DATA.album);
request.setDestinationInExternalFilesDir(activity, createFilePath(), FileNameGetter.getFileName(DATA..url));
// request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
lastDownload= mgr.enqueue(request);
isDownloading = true;
Toasts.pop(activity, "Download Started!!");
// v.setEnabled(false);
// findViewById(R.id.query).setEnabled(true);
}
The problem is that it should be saved on SD Card inside folder "APP_NAME", but once the audio is downloaded, I cant see it inside that folder, and when I play the audio, and check its info, it shows path like thie
/sdcard/Android/data/com.X.app/files/mnt/sdcard/APP_NAME/file.mp3
As its being saved inside data folder, user is not able to see the file. How to fix it to move it to main SD Card i.e. /mnt/sdcard/APP_NAME so that user can see it.
DownloadManager.Request.setDestinationUri(Uri uri) should fit your requirement, remember to call allowScanningByMediaScanner() if you want the MP3 to be scanned by MediaScanner.
Related
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");
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
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
I want to save Image file in Gallery so that Image can be viewed from the Gallery application.
But what I want is to create a separate dir, as like we have for whatsapp Images etc apps in our gallery application.
So far I have written this code to download an image
public void createDir(){
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
Log.d(LOG_TAG, "dir pictr :" + dir.toString());
if (!dir.exists()) {
dir.mkdir();
Log.d(LOG_TAG, "dir not exists and created first time");
} else {
Log.d(LOG_TAG, "dir exists");
}
}
Above code created directory inside gallery dir
Uri imageLink = Uri.parse(downloadUrlOfImage); // this is download link like www.com/abc.jpg
CreateDir();
DownloadManager.Request request = new DownloadManager.Request(imageLink);
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
String absPath = dir.getAbsoultePath();
request.setDestinationUri(Uri.parse(absPath + "image.jpg"));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
But this gives me error as java.lang.IllegalArgumentException: Not a file URI: /storage/sdcard0/Pictures/FreeWee/1458148582.jpg
Basically what I want is to save Image and that image must be shown in Gallery Application under Some directory I named.
If not understood please ask, so that I can improve my question.
How do I proceed further ?
As #RoyFalk pointed out you got 2 issues in your code.
So you can go with this code snippet
String filename = "filename.jpg";
String downloadUrlOfImage = "YOUR_LINK_THAT_POINTS_IMG_ON_WEBSITE";
File direct =
new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.getAbsolutePath() + "/" + DIR_NAME + "/");
if (!direct.exists()) {
direct.mkdir();
Log.d(LOG_TAG, "dir created for first time");
}
DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(downloadUrlOfImage);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(filename)
.setMimeType("image/jpeg")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,
File.separator + DIR_NAME + File.separator + filename);
dm.enqueue(request);
And you will see Image inside the gallery application under your DIR_NAME.
Hope this will help you.
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..