Asynchronous File Download with Progress Bar

Asynchronous File Download with Progress Bar

You should call startDownload() from the UI thread. The whole idea of WebClient.DownloadFileAsync() is that it will spawn a worker thread for you automatically without blocking the calling thread. In startDownload(), you specified callbacks that modify controls which I assume were created by the UI thread. Thus if you call startDownload() from a background thread it will cause problems, because a thread can only modify UI elements it created.

The way it is supposed to work is you call startDownload() from the UI thread, startDownload() as you defined it sets up event call backs that are handled by the UI thread. It then starts the download asynchronously and returns immediately. The UI thread will be notified when the progress changes and the code responsible for updating the progress bar control will execute on the UI thread, and there shouldn't be any problems.

How to use Asynchronous task for download progress dialog in fragment?

I found answer on my own.Hope it will help anybody.

I wanted to call asynch task in fragment and wanted to show progress diolog which will show progress of downloading file in percentage.

1> I called asynch task in class .

DownloadTask.java class

//This is important
public DownloadTask(Context context) {
this.context = context;
mProgressDialog = new ProgressDialog(context);

mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCanceledOnTouchOutside(false);
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void download(String fileUrl, String filepath, String fileName,
Boolean visibility, Boolean choice) {
// Make directories if required
this.fileUrl=fileUrl;
this.filepath=filepath;
this.fileName=fileName;
this.visibility=visibility;
File f = new File(
Environment.getExternalStoragePublicDirectory("/MDroid")
+ filepath);
if (!f.exists())
f.mkdirs();

if (choice == SYSTEM_DOWNLOADER) {

String url=fileUrl;
new MyAsyncTask().execute(url);

} else {
mdroidDownload(fileUrl, fileName);
reqId =0;
}

}

class MyAsyncTask extends AsyncTask<String, String, Void> {

boolean running;

@Override
protected Void doInBackground(String...fUrl) {
int count;

InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {

URL url = new URL(fUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

int lenghtOfFile = connection.getContentLength();

// download the file
input = connection.getInputStream();
output = new FileOutputStream(
Environment.getExternalStorageDirectory() + "/MDroid/"
+ fileName);

//#################################

mydownload(fileUrl, filepath, fileName,
visibility);

//##########################################

byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}

output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;

}

@Override
protected void onPreExecute() {
super.onPreExecute();
running = true;

mProgressDialog.show();
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);

mProgressDialog.dismiss();
}

protected void onProgressUpdate(String... progress) {

// Update the progress dialog
mProgressDialog.setProgress(Integer.parseInt(progress[0]));

}

}

public long mydownload(String fileUrl,String filepath,String fileName,Boolean visibility)
{
DownloadManager manager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);

/* TODO- Offer better alternative. Only a temporary, quick,
* workaround for 2.3.x devices. May not work on all sites.
*/
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
fileUrl = fileUrl.replace("https://", "http://");
Request request = new Request(Uri.parse(fileUrl));
try {
request.setDestinationInExternalPublicDir("/MDroid", filepath
+ fileName);
} catch (Exception e) {
Toast.makeText(context, "External storage not found!",
Toast.LENGTH_SHORT).show();
return 0;
}
request.setTitle(fileName);
request.setDescription("MDroid file download");

// Visibility setting not available in versions below Honeycomb
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
if (!visibility)
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
else
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

// -TODO- save this id somewhere for progress retrieval
reqId = manager.enqueue(request);
return reqId;
}

2>I called this download method from DownloadTask.java class file into my fragment activity like this

// Download if file doesn't already exist
if (!file.exists()) {
fileurl = content.getFileurl();

fileurl += "&token=" + session.getToken();
fName = content.getFilename();

//FROM HERE I AM CALLING ASYNCHRONOUS TASK

DownloadTask dt = new DownloadTask(context);
dt.download(fileurl, path, content.getFilename(), false,
DownloadTask.SYSTEM_DOWNLOADER);

} else {

FileOpener.open(context, file);
}

Download file using HttpClient with ProgressBar

Microsoft recommend you don't use HttpWebRequest for new development; use HttpClient instead.

When you use HttpClient you can get progress like this: Progress bar with HttpClient - essentially to read the stream yourself gradually and calculate how far you've read compared to the content length declared in the header. I'd probably use Bruno's answer

C# Download from url and Custom progress bar

you should use async method to download

   private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample"));
}
else if (radioButton2.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample2"));
}
else if (radioButton3.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample4"));
}
else
{
MessageBox.Show(this, "select radio btn");
}
}

private void Download(Uri uri)
{
Thread thread = new Thread(() =>
{
WebClient client = new WebClient();
client.DownloadProgressChanged += Client_DownloadProgressChanged1;
client.DownloadStringCompleted += Client_DownloadStringCompleted;
client.DownloadStringAsync(uri);
});
thread.Start();
}

private void Client_DownloadProgressChanged1(object sender, DownloadProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate {
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
if(percentage >=10 && percentage <50)
{
textBox1.Text ="message for 10%";
}
else if if(percentage >=50 && percentage <100)
{
textBox1.Text ="message for 50%";
}
else
{
textBox1.Text ="completed";
}
// you can use to show to calculated % of download
});
}

private void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{

BeginInvoke((MethodInvoker)delegate
{
var accounts = e.Result.Split('\n');
textBox1.Text = accounts[new Random().Next(0,accounts.Length)];
});
}

Async ftp file download with progress bar

                pBar.Dispatcher.Invoke(() =>
{
if (GetFileSize(source) <= 0)
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false;
pBar.Maximum = GetFileSize(source);
pBar.Value = 0;
}
});
// code...
pBar.Dispatcher.Invoke(() =>
{
pBar.Value = pBar.Value + readCount;
});

Used dispatcher to update progress bar, works flawlessly



Related Topics



Leave a reply



Submit