I'm downloading a mp3 file from the internet and saving it into the internal storage. The progress of the download is shown in a ProgressDialog. The ProgressDialog displays the progress in percent which is fine. In the right it displays the progress as 1/100 .... I'd like it to display the current size of the file downloaded in MB / the total size of the file being downloaded in MB.
Like in the following picture. The grey text is the current text being displayed. I'd like it to be displayed like the text below it in red.
Here's the current code :
public class DownloadSKHindi extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Downloading");
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
int count = 0;
try {
url = new URL(skURL[10]);
connection = url.openConnection();
connection.connect();
int lengthOfFile = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = getActivity().openFileOutput(file.getPath(), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
}
}
Assuming total is how many bytes are downloaded, and lengthOfFile is the size in bytes of how large the file is. You can do this:
progressDialog.setProgressNumberFormat((bytes2String(total)) + "/" + (bytes2String(lengthOfFile)));
Then using the function bytes2String ( Credit to coder )
private static double SPACE_KB = 1024;
private static double SPACE_MB = 1024 * SPACE_KB;
private static double SPACE_GB = 1024 * SPACE_MB;
private static double SPACE_TB = 1024 * SPACE_GB;
public static String bytes2String(long sizeInBytes) {
NumberFormat nf = new DecimalFormat();
nf.setMaximumFractionDigits(2);
try {
if ( sizeInBytes < SPACE_KB ) {
return nf.format(sizeInBytes) + " Byte(s)";
} else if ( sizeInBytes < SPACE_MB ) {
return nf.format(sizeInBytes/SPACE_KB) + " KB";
} else if ( sizeInBytes < SPACE_GB ) {
return nf.format(sizeInBytes/SPACE_MB) + " MB";
} else if ( sizeInBytes < SPACE_TB ) {
return nf.format(sizeInBytes/SPACE_GB) + " GB";
} else {
return nf.format(sizeInBytes/SPACE_TB) + " TB";
}
} catch (Exception e) {
return sizeInBytes + " Byte(s)";
}
}
Source
Use TextView that is appended after progressDialog inside XML file.
Consider TextView tv = findViewById();
Use this: publishProgress((int) (total * 100 / lengthOfFile), total ,lengthOfFile); to push new data.
And to update the tv use this:
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setProgress(values[0]);
tv.setText((values[1]/(1024*1024)) + "" +(values[1]/(1024*1024)));
}
Related
I want to cancel currently download file from notification area & I want to add cancel button at the bottom of notification download progress. By clicking on that cancel button, download should be cancel. Here is my class DownloadSong using which I perform download file. What modifications I need to do?
public class DownloadSong extends AsyncTask<String, Integer, String> {
Activity activity;
public static String songName, songURL;
private NotificationHelper mNotificationHelper;
public static int notificationID = 1;
boolean download = false;
NotificationManager nm;
public DownloadSong(Activity activity, String songName, String songURL) {
this.activity = activity;
this.songName = songName;
this.songURL = songURL;
mNotificationHelper = new NotificationHelper(activity, songName);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
notificationID++;
mNotificationHelper.createNotification(notificationID);
}
#Override
protected String doInBackground(String... file_URL) {
try {
URL url = new URL(songURL);
HttpURLConnection URLconnection = (HttpURLConnection) url.openConnection();
URLconnection.setRequestMethod("GET");
URLconnection.setDoOutput(true);
URLconnection.connect();
// Detect the file length
int fileLength = URLconnection.getContentLength();
File fSDcard = Environment.getExternalStorageDirectory();
String strSdcardPath = fSDcard.getAbsolutePath();
File fDirectory = new File(strSdcardPath + "/GSD");
if (!fDirectory.exists()) {
fDirectory.mkdir();
}
File fMyFile = new File(fDirectory.getAbsolutePath() + "/" + songName + ".mp3");
Log.e("Download file name ", fMyFile.toString());
FileOutputStream out = new FileOutputStream(fMyFile, true);
InputStream input_File = URLconnection.getInputStream();
byte[] data = new byte[1024];
int total = 0;
int count;
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
out.flush();
out.close();
input_File.close();
} catch (IOException e) {
Log.e("Download Error : ", "Failed");
}
Log.e("Download status", " Complete ");
return null;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(activity, "Song " + "'" + songName + "'" + " downloaded successfully", Toast.LENGTH_LONG).show();
//pDialog.dismiss();
if (download) {
Toast.makeText(activity, "Could Not Connect to Server.", Toast.LENGTH_LONG).show();
mNotificationHelper.clearNotification();
} else
mNotificationHelper.completed();
}
#Override
protected void onProgressUpdate(Integer... progress) {
//pDialog.setProgress(progress[0]);
mNotificationHelper.progressUpdate(progress[0]);
super.onProgressUpdate(progress);
}
}
Most of the time is spent in the loop
while ((count = input_File.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
You can add a check to see if the task is cancelled,
while ((count = input_File.read(data)) != -1 && !isCancelled()) {
total += count;
publishProgress((int) (total * 100 / fileLength));
out.write(data, 0, count);
}
and cancel the download by calling
yourAsyncTask.cancel()
You can cancel asynctask forcefully
Check This
declare your asyncTask in your activity:
private YourAsyncTask mTask;
instantiate it like this:
mTask = new YourAsyncTask().execute();
kill/cancel it like this:
mTask.cancel(true);
I am trying to update a Progress Dialog to increment something like 1-100%. However, nothing ever increments. It always just says 0. Although, I am able to see the numbers print out in my Log Cat and everything ends when it should after 100.
Does anyone see what I am missing? Thanks in advance for any assistance.
private class DownLoadSigTask extends AsyncTask<String, Integer, String> {
private final ProgressDialog dialog = new ProgressDialog(NasStorageNasList.this);
// Set the fileName and filesize to be used later
String fileName = (String) recordItem.get(mPresentDown).get("name");
String filesize = (String) recordItem.get(mPresentDown).get("filesize");
// can use UI thread here
#Override
protected void onPreExecute() {
this.dialog.setMessage("Downloading " + fileName + " from the server. Please wait.");
this.dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.dialog.setCancelable(false);
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
#Override
protected String doInBackground(final String... args) {
// Here is where we need to do the downloading of the
try {
File destDir = new File(LOCALDOWNROOT);
if (!destDir.exists()) {
destDir.mkdirs();
}
File outputFile = new File(destDir, fileName);
Log.e("What is the filename path to download? ", REMOTEDOWNROOT + DATADIRECTORY + fileName);
InputStream fis = sardine.get(REMOTEDOWNROOT + DATADIRECTORY + "/"
+ fileName.replace(" ", "%20"));
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1444];
Log.e("What is the length of the File Size? ", filesize);
long total = 0;
int byteread = 0;
while ((byteread = fis.read(buffer)) != -1) {
downloadTotal += byteread;
// Here is the WHILE LOOP that we will want to give the user
publishProgress((int)(total*100/Long.parseLong(filesize)));
Log.e("CurrentAmount Downloaded: ", String.valueOf((int)(downloadTotal*100/Long.parseLong(filesize))));
// How can I tell the UI the downloaded percentage?
// So, far I am updating the log cat...but nothing for the user.
fos.write(buffer, 0, byteread);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// Just Return null because the void task
return null;
}
// add in a progress bar update
#Override
protected void onProgressUpdate(Integer...progress) {
this.dialog.setProgress(progress[0]);
}
// can use UI thread here
#Override
protected void onPostExecute(final String errMsg) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
Toast.makeText(NasStorageNasList.this, "File Download Done!",
Toast.LENGTH_SHORT).show();
}
}// end DownloadSigTask
You have "typo" mistake. You need to replace in your publishProgress() method total variable with downloadTotal.
publishProgress((int) (downloadTotal * 100 / Long.parseLong(filesize)));
Your total variable is only assigned to zero before loop and is never changed to other value. So you performed division 0 / filesize that will be always 0.
i want to all download video and save in sdcard.i have arraylist in all file.not a single file.how to possible it .please help me.
ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
Thanks in advance!!!
what is pass param in DownloadFileFromURL().i used button click event.
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//what is pass param
new DownloadFileFromURL().execute();
}
});
may download class in below ::
class DownloadFileFromURL extends AsyncTask<Object, String, String> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(Object... params) {
Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
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
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
This link provides an idea on http file download. With that idea, you can iterate through all the video URLs in the list.
In my case i click download button when download all file but in show all file sdcard and some file display . and i used thread .what me wrong in my code : and Cancel(cl) button working but in i used delted download file is not working and {cl and dl button} setVisibitly not changed. My Code Below: Please Helpme>
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
getProgress(pr, position, cl, dl);
// pr.setProgress(getItem(position));
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click");
// dl.setVisibility(View.VISIBLE);
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
//downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag","Start Button Click ");
//
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
//Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
//Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
//Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
}
}
// flushing output
output.flush();
if(!this.download1){
File delete = new File(strDownloaDuRL);
delete.delete();
}
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
//Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
/* cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});*/
}
private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
You can try using the below code to download the files from the url and save into the sdcard:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download url:" + url);
/* 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(5000);
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.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Also keep in mind that you specify the below permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I hope it will help you.
Thanks
i have a running download function. but when i run it, like 80% of the time it make my phone laggy, force close, not responding for a very long time like 1~2 minutes. this case happened very randomly, i cant really trace what is the problem. the device will turn back to normally after the download is complete. i have tried on various devices such as galaxy S2, galaxy note, SE xperia Arc S, and few tables. problem remains the same. can anyone advice me how to improve my code? below is my existing code:
public void onClickDownload(View view){
String url = "http://www.mydomain.com./" + fileURL;
url = url.replaceAll(" ","%20");
String sourceUrl = url;
new DownloadFileAsync().execute(sourceUrl);
}
public class DownloadFileAsync extends AsyncTask<String, Integer, Void> {
private boolean run_do_in_background = true;
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lengthOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lengthOfFile);
File folder = new File(Environment.getExternalStorageDirectory() + "/MaxApps");
boolean success = false;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (!success) {
} else {
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/MaxApps/" + apkURL);
byte data[] = new byte[100*1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){
publishProgress(progressPercent);
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Failed";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), apkURL + " Download Failed.", "Please try again", MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(1, MyN);
run_do_in_background = false;
}
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
notification.contentView.setProgressBar(R.id.pbStatus, 100, progress[0], false);
notificationManager.notify(Integer.parseInt(ID.toString()), notification);
}
#Override
protected void onPostExecute(Void unused) {
if(run_do_in_background) {
notificationManager.cancel(Integer.parseInt(ID.toString()));
Notification MyN = new Notification(); MyN.icon = R.drawable.logo1;
MyN.tickerText = "Download Complete";
MyN.number = 1;
MyN.setLatestEventInfo (getApplicationContext(), "Download Complete, Click to install.", apkURL, MyPI);
MyN.flags |= Notification.FLAG_AUTO_CANCEL;
MyNM.notify(Integer.parseInt(ID.toString()) , MyN);
}
}
}
It might be that updating UI is taking long? Maybe you can try to test like this and see if it makes a difference:
#Override
protected void onProgressUpdate(Integer... progress) {
Log.d("ANDRO_ASYNC", "Progress: " + progress[0]);
}
By the way, this is not related to what you are asking, but I think you have problem in your code that handles the progress:
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent % 5 == 0){
publishProgress(progressPercent);
}
That will update the progress only when it is exactly 5,10,15,20% etc... I guess you actually want to update progress when it is at least %5 further than before.
int previousProgress = 0;
while ((count = input.read(data)) != -1) {
total += count;
int progressPercent = (int) ((total*100)/lengthOfFile);
if(progressPercent - previousProgress >= 5) {
previousProgress = progressPercent;
publishProgress(progressPercent);
}
output.write(data, 0, count);
}