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");
Related
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 wanted to download images that are downloaded from Dropbox and cache them for further use:
String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
//If cache doesn't exist, download the file
mFos = new FileOutputStream(cachePath);
mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);
The mDrawable is null if the code doesn't enter the if block.
If I comment the if condition it works fine. But downloads the images every time.
Edit:
The above code is from how to test for a file in cache
Try this hope helps you
String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
File file = new File(path);
if (file.exists()) {
// File exists
} else {
// File does not exist
}
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()
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.
I am trying to download a file from the internet and it succeeded but now
I want to check if the file exists in the internal storage.
else if (arg0.getId() == R.id.btn_download)
{
Toast.makeText(this, "download button clicked", Toast.LENGTH_SHORT).show();
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(names[b]));
request.setDescription("Downloading..");
request.setTitle("Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex() +1) );
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Futsing Magazine Issue " + (this.mPictureManager.getCurrentIndex()
+1) +".pdf");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
The items retrieved are downloaded to /mnt/sdcard/Download.
How do I check if the file exists or not using code?
Let's say following is your file's path
String path=context.getFilesDir().getAbsolutePath()+"/filename";
File file = new File ( path );
if ( file.exists() )
{
// Toast File is exists
}
else
{
// Toast File is not exists
}
File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS)+ "/"+<file-name>);
if(applictionFile != null && applictionFile.exists()){
}
if file is getting downloads in to default donwload directory