I am trying to create an app that can download music files.
How to download mp3 file in android from a URL and save it in SD card??
I use this code but lenghtOfFile always <=350:
String fileUrl = (String) params[0];
path = (String) params[1];
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
int count;
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection .connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection .getContentLength();
// downlod the file
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
url files :
http://snd1.tebyan.net/1391/12/08_Khaneh_D_117323.mp3
http://snd1.tebyan.net/1393/12/100_Pedar_Va_Madar_D_148797.mp3
and .....
update :
int code= connection.getResponseCode();\\302
String _result= connection.getResponseMessage();\\ found
note :
Files do download in Samsung Galaxy S3, but files do not download in Samsung tablet N8000
You could implement HMTL5 and do it from there, might need some JS...
for 302 response ,you need connection.setInstanceFollowRedirects(true) to follow it. before connection.connect()
Related
I want to install the update automatically as my APK is not on the Play store. So I tried the following:
I followed all the steps given in
http://www.wepstech.com/download-and-install-app-programmatically/
Below is the Async Task: (URL given is correct)
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
String PATH = Objects.requireNonNull(mContext.getExternalFilesDir(null)).getAbsolutePath();
File file = new File(PATH);
boolean isCreate = file.mkdirs();
File outputFile = new File(file, "my_apk.apk");
if (outputFile.exists()) {
boolean isDelete = outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1;
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
fos.write(buffer, 0, len1);
publishProgress((int) ((total * 100) / lenghtOfFile));
}
fos.close();
is.close();
if (mPDialog != null)
mPDialog.dismiss()
;
I have an API checking the version and if the version is old I have given a button to download and install, So when I do that the apk is getting downloaded only (but not a full-size file) I see only 189bytes. The Async just closes thinking the file has downloaded it starts to install and when it does it gives "There was a problem parsing the package".
It is because the APK file not downloaded fully.
I am not sure why the file is not getting downloaded fully. It is an 8MB file. And I am running Android 11.
you can use the lib fetch, it's a best file downloader library for android
https://github.com/tonyofrancis/Fetch
i m making an android app to download pdf files from android and then saving them in a folder in internal or external memory.but sometime due to bad internet connection download stops without finshing .like file size is 1.1mb and its only downloaded upto 750kb. now the problem is whether file fully download or not my app showing it as download but in real it is not.so i want to know the exact size of file befor and after download so that i can found whether file is completely download or not.and want to restart the download.
can anybody help me........
my code
String DownloadUrl = "http://www.example.com/books/"+book_name;
String fileName = book_name;
URL url = new URL(DownloadUrl);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
// File SDCardRoot = new File("/storage/emulated/0/documents/docx/stuff/");
File SDCardRoot = new File(Environment.getExternalStorageDirectory()+File.separator+"MybookStore/paper/paperStuff/documents/docx/other/stuff/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,fileName);
String file_size = Long.toString(file.length()/1024);
int size_file=Integer.parseInt(file_size);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
my code
Any reasonable server response header will include a Content-Length key, which will hopefully denote the full length of the resource you’re trying to download.
With that in mind, here's a quick example:
HttpURLConnection connection = null;
InputStream input = null;
OutputStream output = null;
try {
final URL url = new URL(resourceUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
final int length = connection.getContentLength();
int downloaded = 0;
input = url.openStream();
output = new FileOutputStream(targetFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
}
if (downloaded == length) {
// The file was successfully downloaded.
} else {
// The file was not fully downloaded.
}
} catch (IOException e) {
// Handle exception.
} finally {
// Close resources.
}
my code works fine, it downloads image to sd card, however , i get this warning where i defined my sd card path "Do not hardcode "/sdcard/"; use Environment.getExternalStorageDirectory().getPath() instead"
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/.temp");//.temp is the image file name
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
}
the problem is, if i use the suggested solution, then i won't be able to give my downloaded file a new name (".temp")
When working with files and directories, it's better to work with File objects rather than with strings. Here's how you can address the warning:
File dir = Environment.getExternalStorageDirectory();
File tmpFile = new File(dir, ".temp");
OutputStream output = new FileOutputStream(tmpFile);
That creates a File object that points to a file named ".temp" in the environment's external storage directory. It then opens it for writing using a different constructor of the FileOutputStream class.
If you need the file path as a string instead (say, for printing), you can do that too:
String tmpFileString = tmpFile.getPath();
Or if you decide to use the java.nio API in the future and need a Path object:
Path tmpFilePath = tmpFile.toPath();
I have application for Android, that downloading files from remote server. And my app downloading files much more slowly as ios application the same file at the same Internet connection.
That my code:
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
FileOutputStream output =
context.openFileOutput(new File(context.getFilesDir(), fileName).getName(), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(String.valueOf((int) ((total * 100) / lenghtOfFile)));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
What can help in solving this problem.
My application needs to download some big Files. I use a service for the download an show the progress in a notification. The problem is that during that download time the user can switch from 3g to WIFI. In that case the progress stops but no exception is thrown.
How do I handle this situation properly?
URL url = new URL(myurl);
URLConnection conexion = url.openConnection();
conexion.setReadTimeout(10000);
conexion.setConnectTimeout(10000);
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(targetFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
updateProgress(downloadNM, downloadNotification, (int)total*100/lenghtOfFile);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Take a look at the HttpClient-Library. It provides much more options than the URL class, and might help you with your problem.
http://developer.android.com/reference/org/apache/http/client/HttpClient.html