Check the request.setDestination functions here To Store file in External App-Specific Directory [example: "external/Android/data/your_app_name/filePath_you_set_in_function”], use like below:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Selected Video is being downloaded");
request.allowScanningByMediaScanner();
request.setTitle("Downloading Video");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName); //To Store file in External Public Directory use "setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)"
DownloadManager manager = (DownloadManager)
mContext.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
And if you want to download it to another place you need to move it after your download gets finished, by using IO streams. You can use a broadcast receiver to perform this task once the DownloadManager has finished downloading. You can use FileProvider to open the file with another app in Android version 10 or above.
Answer from Akki on Stack OverflowCheck the request.setDestination functions here To Store file in External App-Specific Directory [example: "external/Android/data/your_app_name/filePath_you_set_in_function”], use like below:
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDescription("Selected Video is being downloaded");
request.allowScanningByMediaScanner();
request.setTitle("Downloading Video");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, fileName); //To Store file in External Public Directory use "setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)"
DownloadManager manager = (DownloadManager)
mContext.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
And if you want to download it to another place you need to move it after your download gets finished, by using IO streams. You can use a broadcast receiver to perform this task once the DownloadManager has finished downloading. You can use FileProvider to open the file with another app in Android version 10 or above.
simply add this line to save file:
request.setDestinationInExternalFilesDir(context,Environment.DIRECTORY_ALARM,mp3name);
to delete this file
File file = new
File(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");
file.delete();
to read this file
File file= newFile(context.getExternalFilesDir(Environment.DIRECTORY_ALARMS),"Fav_Ringtone.mp3");
Videos
Consider using Picasso for your purpose. I'm using it in one of my project. To save image on external disk you can use following:
Picasso.with(mContext)
.load(ImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
From here you can download this library.
You can download th image from an url like this:
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
And you may then want to save the image so do:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
I can not believe i solved this. What I do is replacing:
getFilesDir()
to
Environment.getExternalStorageDirectory()
below I post my final code
class DownloadFileFromURL extends AsyncTask<String, String, String> {
ProgressDialog pd;
String pathFolder = "";
String pathFile = "";
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(DashboardActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setMax(100);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(true);
pd.show();
}
@Override
protected String doInBackground(String... f_url) {
int count;
try {
pathFolder = Environment.getExternalStorageDirectory() + "/YourAppDataFolder";
pathFile = pathFolder + "/yourappname.apk";
File futureStudioIconFile = new File(pathFolder);
if(!futureStudioIconFile.exists()){
futureStudioIconFile.mkdirs();
}
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lengthOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
FileOutputStream output = new FileOutputStream(pathFile);
byte data[] = new byte[1024]; //anybody know what 1024 means ?
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lengthOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return pathFile;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pd.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String file_url) {
if (pd!=null) {
pd.dismiss();
}
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(i);
}
}
Simply put this code to use this class
new DownloadFileFromURL().execute("http://www.yourwebsite.com/download/yourfile.apk");
This code can perform file download to your internal phone storage with a progress bar and continue asking your permission for application install.
Enjoy it.
as we know getFilesDir() returns the absolute path to the directory on the filesystem where files created, which will give you path /data/data/your package/files
so you can find the file(if downloaded completely) there
i suggest you to read this article:
How to get the each directory path
If you are looking for saving image once and reusing it many times this may help you Google Volley Library. Universal Image Loader which is widely used after Volley.
EDIT : Now there are bunch of libaries which are so popular.
- Picasso
- Glide
- Fresco
Choose according to your requirement.Here is comparison.
You can store url in table and check your condition whatever download file from server and store it in external/internal storage.
Try having a look at
_context.getFilesDir();
and
_context.getExternalFilesDir();
/** * Copies a private raw resource content to a publicly readable * file such that the latter can be shared with other applications. */
private void copyPrivateRawResourceToPubliclyAccessibleFile() { InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = getResources().openRawResource(R.raw.robot); outputStream = openFileOutput(SHARED_FILE_NAME, Context.MODE_WORLD_READABLE | Context.MODE_APPEND); byte[] buffer = new byte[1024]; int length = 0; try { while ((length = inputStream.read(buffer)) > 0){ outputStream.write(buffer, 0, length); } } catch (IOException ioe) { /* ignore */ } } catch (FileNotFoundException fnfe) { /* ignore */ } finally { try { inputStream.close(); } catch (IOException ioe) { /* ignore */ } try { outputStream.close(); } catch (IOException ioe) { /* ignore */ } } }