In my android app I must download some video from url. For this I use this function :
private void saveVideoToSDcard(String video) throws IOException {
URL url = new URL(video);
long startTime = System.currentTimeMillis();
String name = video.substring(video.lastIndexOf("/") + 1);
System.out.println("image download beginning: " + name);
// Open a connection to that URL
ucon = url.openConnection();
// this timeout affects how long it takes for the app to realize there's
// a connection problem
ucon.setReadTimeout(TIMEOUT_CONNECTION);
ucon.setConnectTimeout(TIMEOUT_SOCKET);
// Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/Downloads/"
+ name);
byte[] buff = new byte[5 * 1024];
// Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1) {
outStream.write(buff, 0, len);
}
// clean up
outStream.flush();
outStream.close();
inStream.close();
System.out.println("download completed in "
+ ((System.currentTimeMillis() - startTime) / 1000) + " sec");
}
and I call this function on onCreate() method :
for (int j = 0; j < jArray.length(); j++) {
if (target[j].endsWith(".mp4")) {
System.out.println("video de downloadat");
String name = target[j]
.substring(target[j].lastIndexOf("/") + 1);
try {
saveVideoToSDcard(target[j]);
target[j] = Environment.getExternalStorageDirectory()
+ "/Downloads/" + name;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
where target[] is an array that contains the video's url.
The videos are downloaded on Downloads folder, but I have this problem : for a moment I downloaded 2 videos : first video has duration 1:17 and second video has duration 2:38. If I open first video it plays for 10 seconds and after that it close unexpectedly. The second video doesn't have this problem, it works fine. Do you have any idea why I have this problem ?
Any idea is welcome. Thanks in advance.
Related
I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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();
} catch (Exception e) {
}
return null;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.
I have a list view. When user selects an item of my list view, I open DetailActivity that user can download a file in that activity and I show the user download percentage using ProgressWheel.
My problem is when user closes the activity and then returns back to activity, the ProgressWheel doesn't update anymore.
Here is my code:(I download the file using AsynchTask)
/**
* Background Async Task to download file
* */
class DownloadTask extends AsyncTask<String, String, Boolean> {
/**
* Downloading file in background thread
* */
#Override
protected Boolean doInBackground(String... params) {
try {
URL url = null;
try {
String link = params[0];
fileExtention = getFileExtention(link);
url = new URL(link);
} catch (Exception e) {
e.printStackTrace();
return false;
}
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set some parameters for httpUrlConnection
connection.setConnectTimeout(JSONConstants.CONNECTION_TIMEOUT);
connection.setReadTimeout(JSONConstants.READ_TIMEOUT);
connection.connect(); // Connection Complete here.!
// Get from Server and Catch In Input Stream Object.
InputStream inputStream = connection.getInputStream();
int lenghtOfFile = connection.getContentLength();
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
File file = new File(PATH);
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, "fileTitle"
+ ".mp3" );
FileOutputStream fileOutputStream = new FileOutputStream(
outputFile);
byte[] buffer = new byte[4096];
int length = 0;
long total = 0;
while ((length = inputStream.read(buffer)) != -1) {
total += length;
// publishing the progress....
// After this onProgressUpdate will be called
if (lenghtOfFile > 0)
publishProgress(""
+ (int) ((total * 100) / lenghtOfFile));
// Write In FileOutputStream.
fileOutputStream.write(buffer, 0, length);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void publishProgress(String percent) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
downloadProgressWheel.setProgress(Integer.valueOf(percent));
}
How can I set my ProgressWheel still updated when user returns back to it's associated activity.
I want to download a video file (extension 3gp) from a certain http address. My application starts downloading, but it stops after downloading 9216 bytes. The file length is 1734741. I tried to increase the heap (because I got some warning about increasing the heap size) by including the following line in the Manifest file:
android:largeHeap="true"
It does not help. Here is the fragment of the java code that deals with downloading:
protected String doInBackground(String... sUrl) {
byte[] data = new byte[8];
double total = 0;
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
Log.v("Here","the address is " + sUrl[0]);
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("File ", "length = " + connection.getContentLength());
// this will be useful so that you can show a typical 0-100% progress bar
double fileLength = (Math.log10((double)connection.getContentLength()));
Log.v("DoInBackground","file length = " + fileLength);
if (fileLength <= 0)
fileLength = (long)(Math.log10(1734741.0));
Log.v("DoInBackground","again file length = " + fileLength);
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
Log.v("Input ","is " + input);
Log.v("Output ","is " + Environment.getExternalStorageDirectory().getPath());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos); /////????????
int i = (int)(Math.pow(10,(Math.log10(total) + 2 - fileLength)));
while ((count = input.read(data)) != -1) {
Log.v("Count","= " + count);
total += count;
Log.v("Total " + total,"Count " + count);
// publishing the progress....
if ((int)(total * 100 / fileLength) == 0)
i = i + 1;
Log.v("Progress","Increment" + i);
/////////////task.publishProgress(i);
prgs.setProgress(i);
SystemClock.sleep(1000);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException ioe) {
ioe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
The application uses a Progress Bar to show the progress of the download. Because the file length is quite big (1734741 bytes), I did logarithmic calculations. Also, I have several Log.v messages to see what's going on, I hope this does not hamper understanding of the code.
Anyway, my question refers only to the incomplete downloading of the 3gp file.
What can I do to download the video file? Any idea? Thanks in advance for the help.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
File download with android
How do I download a .txt file from the internet at a given URL and save it to the phone in Android? It can be saved to either internal storage, SD storage, or anywhere really accessible for the app to use.
The URL I have been using for testing with loading URL WebViews is http://base.google.com/base/products.txt
This should do the trick. It downloads the file to sdcard/Download/products.txt. You can change it below.
try {
URL url = new URL("http://base.google.com/base/products.txt");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/products.txt");
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
/*publishProgress("" + progress_temp); //only for asynctask
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}*/
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e) {
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
}
I having problem with file download,
I am able to download file in emulator but It is not working with the phone.
I have defined the permission for the Internet and write SD card.
I having one doc file on server, and if user click on download. It downloads the file. This works fine in emulator but not working in phone.
Edit
My code for download file
public void downloadFile(String _url, String fileName) {
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
PATH.mkdirs();
URL url = new URL(_url); // you can write here any link
File file = new File(PATH, fileName);
long startTime = System.currentTimeMillis();
Log.d("Manager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
try the snippets given bellow...
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
_url = _url.replace(" ", "%20");
URL url = new URL(_url);
//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();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATH,fileName);
//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();
Log.i("Download", totalSize+"");
//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);
}
//close the output stream when done
fileOutput.close();
return true;
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
make sure you have enters the correct download path(url)