You cannot use DownloadManager to download directly to your app's portion of internal storage. You will need to use OkHttp or some other in-process HTTP client API.
You cannot use DownloadManager to download directly to your app's portion of internal storage. You will need to use OkHttp or some other in-process HTTP client API.
You can simple just delete this line, request.setDestinationInExternalFilesDir()
By default, downloads are saved to a generated filename in the shared download cache
From Docs
For download you have to use async task.
like in this example I am downloading mutliple file it can be PDF, Image etc
class DownloadFileAsync(paths: Array<String?>, listener: AsyncResponse?, size: Int) : AsyncTask<String, String, Array<String?>>() {
private val listener: AsyncResponse? = listener
var current = 0
var paths: Array<String?>
val downPaths = arrayOfNulls<String>(size)
lateinit var fpath: String
var show = false
init {
this.paths = paths
}
protected override fun onPreExecute() {
super.onPreExecute()
}
protected override fun doInBackground(vararg aurl: String): Array<String?> {
val rows = aurl.size
while (current < rows) {
var count: Int
try {
println("Current: " + current + "\t\tRows: " + rows)
fpath = getFileName(this.paths[current]!!)
val url = URL(this.paths[current])
val conexion = url.openConnection()
conexion.connect()
val lenghtOfFile = conexion.getContentLength()
val input = BufferedInputStream(url.openStream(), 512)
val file = File(Environment.getExternalStorageDirectory().path.plus(File.separator).plus(fpath))
downPaths.set(current, file.absolutePath)
if (!file.exists()) file.createNewFile()
val output = FileOutputStream(file)
val data = ByteArray(512)
var total: Long = 0
while (true) {
count = input.read(data)
if (count == -1) break
total += count
output.write(data, 0, count)
}
show = true
output.flush()
output.close()
input.close()
current++
} catch (e: Exception) {
Log.d("Exception", "" + e)
}
} // while end
onPostExecute(downPaths)
return downPaths
}
override fun onProgressUpdate(progress: Array<String?>) {
}
override fun onPostExecute(result: Array<String?>) {
listener?.processFinish(result)
}
private fun getFileName(wholePath: String): String {
var name: String? = null
val start: Int
val end: Int
start = wholePath.lastIndexOf('/')
end = wholePath.length //lastIndexOf('.');
name = wholePath.substring((start + 1), end)
return name
}
}
After that I am geting the call back of file path via interface listener?.processFinish(result)
Note: Maybe I should use comment section for this, but my reputation is still low so...
I try running your code, the only thing missing is on the download function. It should be:
val destinationInExternalPublicDir = request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile)
Your path is only valid for your app. Place the file in a place where other apps can 'see' it. Use GetExternalFilesDir() or getExternalStorageDirectory().
Note about files which are created inside the directory created by Context.getDir(String name, int mode) that they will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
So you can use Context.openFileOutput(String name, int mode). I'm re-using your code for an example:
try {
// Now we use Context.MODE_WORLD_READABLE for this file
FileOutputStream fos = openFileOutput(outputFileName,
Context.MODE_WORLD_READABLE);
// Download data and store it to `fos`
// ...
You might want to take a look at this guide: Using the Internal Storage.
The possible reason is the folder in which you want to does not exist. First check if it exist. Create it if not. Then create fileoutputstream and write to it.
I suggest you use the DownloadManager. There are too many problems that can arise during download to handle all of them yourself. Just think of temporary loss of connectivity in the middle of download... Below is some code I pulled out of my app and slightly modified to get rid of parts you don't need.
public void downloadAndOpenPdf(String url,final File file) {
if(!file.isFile()) {
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url));
req.setDestinationUri(Uri.fromFile(file));
req.setTitle("Some title");
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
unregisterReceiver(this);
if (file.exists()) {
openPdfDocument(file);
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
dm.enqueue(req);
Toast.makeText(this, "Download started", Toast.LENGTH_SHORT).show();
}
else {
openPdfDocument(file);
}
}
public boolean openPdfDocument(File file) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(target);
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this,"No PDF reader found",Toast.LENGTH_LONG).show();
return false;
}
}