How to get the time of download - android

I need to get the time of download when I launch my android application. So, I added 2 Log and System.currentTimeMillis(). But, I can’t find the exact location to put these tools.
To get the start time, I added this :
period=System.currentTimeMillis();
System.out.println("Début téléchargement : "+System.currentTimeMillis());
To ser the end time, I added this :
System.out.println("Fin téléchargement : "+System.currentTimeMillis());
period=(System.currentTimeMillis()-period);
System.out.println("La durée de téléchargement : "+period+"ms");
And this is all the code to download file :
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
File vSDCard = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
vSDCard = Environment.getExternalStorageDirectory();
File vFile = new File(vSDCard.getParent() + "/" + vSDCard.getName() + "/"
+ "image.jpg");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
conexion.connect();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(vFile);
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) {
Log.d("ImageManager", "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
ProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
I need your suggestion please.

First block before open URL connection or just before you start reding from input stream.
Second block after close of connection or just after the loop.
What's so difficult about it? Am I missing something ?

Related

Android Asynctask get last progress in background after destroy activity

What I want to do now is loop download pdf from URL that has about 875 Files.
I have already done this by using Asynctask and update the progress in progress dialog also everything is working fine, but what I had a problem is when the user clicks on my DOWNLOAD IN BACKGROUND button, the download is still going on and then I want to re-open the activity again. but the progress and name of the file that displays to the user is not showing anymore.
I know that when we start new activity it will ignore the background running process of our last Asynctask, so how could we solve this problem? (sorry for my English, it's my first time through on StackOverflow)
my code is similar to this
Here sample of my code:
class DownloadFileFromURL extends AsyncTask<ArrayList<LawDocument>,Integer, String> {
private boolean running = true;
Exception error;
#Override
protected void onPreExecute() {
super.onPreExecute();
if(haveNetworkConnection()){
showDialog(progress_bar_type);
}else {
running = false;
showdailog();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
running = false;
}
#Override
protected String doInBackground(ArrayList<LawDocument>[] f_url) {
ArrayList<LawDocument> passed = f_url[0]; //get passed arraylist
System.out.println("Data::" + passed.size());
int count;
InputStream input = null;
OutputStream output = null;
while(!isCancelled()) {
try {
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
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((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
runOnUiThread(new Runnable() {
#Override
public void run() {
pDialog.setMessage(countfile+" / "+ConstantClass.filecount);
}
});
}
}
} catch (Throwable t) {
Log.e("AsyncTask", "OMGCrash", t);
// maybe throw it again
Toast.makeText(DownloadLoading.this,"There is a problem",Toast.LENGTH_SHORT).show();
throw new RuntimeException(t);
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(Integer... progress) {
// setting progress percentage
pDialog.setProgress(progress[0]);
}
/**
* After completing background task Dismiss the progress dialog
**/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
//dismissDialog(progress_bar_type);
if (error !=null){
Toast.makeText(DownloadLoading.this, error.getMessage(),
Toast.LENGTH_SHORT).show();
}else if(!running){
Log.d("Faild","Download fail connection");
}else{
Toast.makeText(DownloadLoading.this, "Success", Toast.LENGTH_SHORT).show();
}
}
}
}
}
I guess the Best solution to you is using Service with BroadCast
which Mean but all your download In Service
lets say
public class DowloadService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle extras = intent.getExtras();
your_data = extras.get() // just example
for (int i = 0; i < passed.size(); i++) {
File file = getBaseContext().getFileStreamPath(passed.get(i).getActualFilename());
if (file.exists()){
countfile+=1;
pDialog.setMessage(" Exist / "+ConstantClass.filecount);
}else{
Log.d("checkFilecount" + i, "fileName: " + passed.get(i).getFileName());
String filename = passed.get(i).getFileName().substring(passed.get(i).getFileName().lastIndexOf("/") + 1);
Log.d("checkFile", "name: " + filename);
URL url = new URL(passed.get(i).getFileName());
System.out.println("Data::" + passed.get(i).getFileName());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
input = new BufferedInputStream(url.openStream(), 8192);
//input = new BufferedInputStream(url.openStream(), 20000);
System.out.println("Data::" + passed.get(i).getFileName());
System.out.println("Data::" + filename);
// Output stream to write file
output = new FileOutputStream(getApplicationContext().getFilesDir() + "/" + filename);
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((int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
countfile+=1;
// send broadcast with data you want
ntent.putExtra("dataType",dataType);
intent.putExtra("getAccuracy",gpsSignal);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
});
return START_NOT_STICKY;
}
}
and then in your activiy Setup Local BroadCast To get Data send
private class BroadCastLocal extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
if (Constrains.PEDOMETERBROADCAST.equalsIgnoreCase(intent.getAction()))
{
int dataType = intent.getIntExtra("dataType",-1);
}
}
Now whenever the user start/end your activity .. the process will not be effected

Android - Cannot play audio after downloading from Url because of wrong data source. How to solve this?

I have downloaded an audio file from Url thanks to Giridharan's answer in the link below:
Android - Save image from URL onto SD card
The problem is that I cannot play it, the error is as follows:
java.io.IOException: setDataSourceFD failed.: status=0x80000000
I'm sure that the audio url on the Internet is working fine, because I can play audio directly from that Url without downloading, but after download it then cannot play anymore, maybe the data source was changed incorrectly while downloading.
So how to solve this problem? Any help will be appreciated! Thanks for reading.
Download Audio from web using below code.
private void startDownload() {
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
// Smaple url String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// create dialog if you want
}
#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/myAudio.mp3");
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;
}
#Override
protected void onPostExecute(String unused) {
// hide/dismiss dialog if you have any
}
}
then play it using /sdcard/myAudio.mp3 path in your media player.
if have any issue see this thread.
Finally I found the solution to my question, and now I post here to help everyone else faces the same problem can overcome it.
public String downloadAudioFromUrl(String url) {
int count;
File file = null;
try {
URL urls = new URL(url);
URLConnection connection = urls.openConnection();
connection.connect();
// this will be useful to show the percentage 0-100% in progress bar
int lengthOfFile = connection.getContentLength();
File storageDir = new File(Environment.getExternalStorageDirectory().toString() + "/Photo_Quiz/Audio");
if (!storageDir.exists()) {
storageDir.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
String filename = "audio_" + timeStamp + ".3gp";
file = new File(storageDir, filename);
InputStream input = new BufferedInputStream(urls.openStream());
OutputStream output = new FileOutputStream(file.getAbsolutePath());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress...
// publishProgress((int) (total * 100 / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
notifyNewMediaFile(file);
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}

ProgressDialog of AsyncTask

Hi I need to show summary progress of AsyncTask. I want to show ProgressBar or ProgressDialog of Downloading, but I have know idea what to do, I know how to show dialog, but only when I download one file, and how do when I have a lot of files to download. Can somebody help????
Here is My AyncTaskClass
public class DownloadProgramTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
String path = sUrl[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(path);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
}
And I create new instance of that class for every execute,
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK", MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
File imgLargeFile = new File(dirImageLarge, a.getId() + ".png");
if (!imgLargeFile.exists()) {
imgLargeList.add(a.getVoice());
new DownloadProgramTask().execute(MYurl.BASE_URL + "/" + a.getImgLarge(), imgLargeFile.getPath());
}
you can use the overridden method OnProgressUpdate of Async Task. call publishProgress in doingBackground of asynctask with interger
something like this..
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.i("makemachine", "onProgressUpdate(): " +
percentBar.setProgress((values[0] * 2) + "%");
}

Android updating progress doesn't work while downloading LARGE files

I have read this topic
and I have a problem about downloading large files, because progress dialog does not upload progress or upload only once after downloading and show 100% suddenly. But all works perfectly when I'm downloading small files.
I think problem may be here:
publishProgress((int)(total*100/fileLength));
My code:
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePat();
File dir = new File(sdpath + "/Myfolder");
dir.mkdir();
OutputStream output = new FileOutputStream(dir.toString() + "/" + "myfilename");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total/fileLength)*100);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
My file is about 80 mb.
You should try to divide first :
publishProgress((int)(total/fileLength)*100);
as you can get an out of range division.

android AsyncTask using HttpURLConnection lenghtOfFile is -1 need help

i am trying to download mp file in back ground using AsyncTask into the emulator it works properly.. but in divice it doesn't show the progressbar
this problem is due to the when i am running this code the
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
that gives me -1 why this happning? my code is
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// mp3load();
int len1 = 0;
int count;
try {
URL url = new URL(GlobalVariable.Getstr());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v(LOG_TAG, "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
// String fileName = "workTest.mp3";
String fileName = GlobalVariable.Getstrpath().toString();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
long total = 0;
while ((count = is.read(buffer)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// fos.write(buffer, 0, len1);
fos.write(buffer, 0, count);
}
fos.close();
is.close();
} catch (IOException e) {
Log.d(LOG_TAG, "Error: " + e);
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
refreshList();
Toast.makeText(
FindFilesByType.this,
"Downloading of " + GlobalVariable.Getstrpath()
+ " complete.", Toast.LENGTH_LONG).show();
// Intent i = new Intent(FindFilesByType.this, SongList.class);
// finish();
// startActivity(i);
try{
Intent i = new Intent(FindFilesByType.this, SongList.class);
finish();
startActivity(i);}catch (Exception e) {
// TODO: handle exception
}
}
}
the entiere code works fine for emulator
but it always doesn't display me progress but download happens sucessfully thanks Pragna
Somethimes java can't retrive the size of a remote file, and i think that is your problem.
But please check internet connection on your phone when debugging the code.
Got the same problem (on Android 4.0 only), and removing
c.setDoOutput(true);
fixed it for me.

Categories

Resources