Java 使用 Android 下载文件,并在 ProgressDialog 中显示进度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3028306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download a file with Android, and showing the progress in a ProgressDialog
提问by Tom Leese
I am trying to write a simple application that gets updated. For this I need a simple function that can download a file and show the current progressin a ProgressDialog
. I know how to do the ProgressDialog
, but I'm not sure how to display the current progress and how to download the file in the first place.
我正在尝试编写一个可以更新的简单应用程序。为此,我需要一个简单的功能,可以下载一个文件,并显示当前进度的ProgressDialog
。我知道该怎么做ProgressDialog
,但我不确定如何显示当前进度以及如何首先下载文件。
采纳答案by Cristian
There are many ways to download files. Following I will post most common ways; it is up to you to decide which method is better for your app.
下载文件的方法有很多种。下面我将发布最常见的方式;由您决定哪种方法更适合您的应用程序。
1. Use AsyncTask
and show the download progress in a dialog
1.使用AsyncTask
并在对话框中显示下载进度
This method will allow you to execute some background processes and update the UI at the same time (in this case, we'll update a progress bar).
此方法将允许您同时执行一些后台进程并更新 UI(在本例中,我们将更新进度条)。
Imports:
进口:
import android.os.PowerManager;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
This is an example code:
这是一个示例代码:
// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true); //cancel the task
}
});
The AsyncTask
will look like this:
该AsyncTask
会是这样的:
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
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("/sdcard/file_name.extension");
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;
}
The method above (doInBackground
) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate
and onPreExecute
run on the UI thread, so there you can change the progress bar:
上面的方法 ( doInBackground
) 总是在后台线程上运行。你不应该在那里做任何 UI 任务。另一方面,onProgressUpdate
和onPreExecute
在 UI 线程上运行,因此您可以更改进度条:
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
For this to run, you need the WAKE_LOCK permission.
为此,您需要 WAKE_LOCK 权限。
<uses-permission android:name="android.permission.WAKE_LOCK" />
2. Download from Service
2. 从服务下载
The big question here is: how do I update my activity from a service?. In the next example we are going to use two classes you may not be aware of: ResultReceiver
and IntentService
. ResultReceiver
is the one that will allow us to update our thread from a service; IntentService
is a subclass of Service
which spawns a thread to do background work from there (you should know that a Service
runs actually in the same thread of your app; when you extends Service
, you must manually spawn new threads to run CPU blocking operations).
这里的大问题是:如何从服务更新我的活动?. 在下一个示例中,我们将使用两个您可能不知道的类:ResultReceiver
和IntentService
。ResultReceiver
是允许我们从服务更新线程的那个;IntentService
是它的一个子类,Service
它从那里产生一个线程来做后台工作(你应该知道 aService
实际上在你的应用程序的同一个线程中运行;当你扩展时Service
,你必须手动产生新线程来运行 CPU 阻塞操作)。
Download service can look like this:
下载服务看起来像这样:
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
@Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
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(connection.getInputStream());
String path = "/sdcard/BarcodeScanner-debug.apk" ;
OutputStream output = new FileOutputStream(path);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Add the service to your manifest:
将服务添加到您的清单中:
<service android:name=".DownloadService"/>
And the activity will look like this:
活动将如下所示:
// initialize the progress dialog like in the first example
// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
Here is were ResultReceiver
comes to play:
这是ResultReceiver
来玩的:
private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
dialog.setProgress(progress);
if (progress == 100) {
dialog.dismiss();
}
}
}
}
2.1 Use Groundy library
2.1 使用 Groundy 库
Groundyis a library that basically helps you run pieces of code in a background service, and it is based on the ResultReceiver
concept shown above. This library is deprecatedat the moment. This is how the wholecode would look like:
Groundy是一个基本上可以帮助您在后台服务中运行代码片段的库,它基于上述ResultReceiver
概念。该库目前已弃用。这就是整个代码的样子:
The activity where you are showing the dialog...
您在其中显示对话框的活动...
public class MainActivity extends Activity {
private ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
Groundy.create(DownloadExample.this, DownloadTask.class)
.receiver(mReceiver)
.params(extras)
.queue();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
});
}
private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
switch (resultCode) {
case Groundy.STATUS_PROGRESS:
mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
break;
case Groundy.STATUS_FINISHED:
Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
mProgressDialog.dismiss();
break;
case Groundy.STATUS_ERROR:
Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
break;
}
}
};
}
A GroundyTask
implementation used by Groundyto download the file and show the progress:
一个GroundyTask
使用实施Groundy下载文件,并显示进度:
public class DownloadTask extends GroundyTask {
public static final String PARAM_URL = "com.groundy.sample.param.url";
@Override
protected boolean doInBackground() {
try {
String url = getParameters().getString(PARAM_URL);
File dest = new File(getContext().getFilesDir(), new File(url).getName());
DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
return true;
} catch (Exception pokemon) {
return false;
}
}
}
And just add this to the manifest:
只需将其添加到清单中:
<service android:name="com.codeslap.groundy.GroundyService"/>
It couldn't be easier I think. Just grab the latest jar from Githuband you are ready to go. Keep in mind that Groundy's main purpose is to make calls to external REST apis in a background service and post results to the UI with easily. If you are doing something like that in your app, it could be really useful.
我想这再简单不过了。只需从 Github获取最新的 jar ,您就可以开始了。请记住,Groundy的主要目的是在后台服务中调用外部 REST api,并轻松地将结果发布到 UI。如果你在你的应用程序中做类似的事情,它可能真的很有用。
2.2 Use https://github.com/koush/ion
2.2 使用https://github.com/koush/ion
3. Use DownloadManager
class (GingerBread
and newer only)
3. 使用DownloadManager
类(GingerBread
仅限更新版本)
GingerBread brought a new feature, DownloadManager
, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system.
GingerBread 带来了一个新功能,DownloadManager
它允许您轻松下载文件并将处理线程、流等的繁重工作委托给系统。
First, let's see a utility method:
首先,让我们看看一个实用方法:
/**
* @param context used to check the device version and DownloadManager information
* @return true if the download manager is available
*/
public static boolean isDownloadManagerAvailable(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return true;
}
return false;
}
Method's name explains it all. Once you are sure DownloadManager
is available, you can do something like this:
方法的名称说明了一切。一旦确定DownloadManager
可用,您可以执行以下操作:
String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Download progress will be showing in the notification bar.
下载进度将显示在通知栏中。
Final thoughts
最后的想法
First and second methods are just the tip of the iceberg. There are lots of things you have to keep in mind if you want your app to be robust. Here is a brief list:
第一种和第二种方法只是冰山一角。如果您希望您的应用程序健壮,您必须记住很多事情。这是一个简短的列表:
- You must check whether user has an internet connection available
- Make sure you have the right permissions (
INTERNET
andWRITE_EXTERNAL_STORAGE
); alsoACCESS_NETWORK_STATE
if you want to check internet availability. - Make sure the directory were you are going to download files exist and has write permissions.
- If download is too big you may want to implement a way to resume the download if previous attempts failed.
- Users will be grateful if you allow them to interrupt the download.
- 您必须检查用户是否有可用的互联网连接
- 确保您拥有正确的权限(
INTERNET
和WRITE_EXTERNAL_STORAGE
);同样ACCESS_NETWORK_STATE
,如果你想检查网络可用性。 - 确保您要下载文件的目录存在并且具有写入权限。
- 如果下载太大,您可能需要实现一种在之前尝试失败的情况下恢复下载的方法。
- 如果您允许他们中断下载,用户将不胜感激。
Unless you need detailed control of the download process, then consider using DownloadManager
(3) because it already handles most of the items listed above.
除非您需要对下载过程进行详细控制,否则请考虑使用DownloadManager
(3),因为它已经处理了上面列出的大部分项目。
But also consider that your needs may change. For example, DownloadManager
does no response caching. It will blindly download the same big file multiple times. There's no easy way to fix it after the fact. Where if you start with a basic HttpURLConnection
(1, 2), then all you need is to add an HttpResponseCache
. So the initial effort of learning the basic, standard tools can be a good investment.
但也要考虑到您的需求可能会发生变化。例如,DownloadManager
没有响应缓存。它会盲目地多次下载同一个大文件。事后没有简单的方法来修复它。如果您从基本的HttpURLConnection
(1, 2) 开始,那么您只需要添加一个HttpResponseCache
. 因此,最初学习基本标准工具的努力可能是一项不错的投资。
This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app's UI. Alternatively, you can use a notification to inform the user of the task's progress. For more details Link
此类在 API 级别 26 中已弃用。ProgressDialog 是一个模式对话框,可防止用户与应用程序交互。您应该使用进度指示器(如 ProgressBar),而不是使用此类,它可以嵌入到您的应用程序的 UI 中。或者,您可以使用通知来通知用户任务的进度。欲知更多详情链接
回答by Mnightmare
Don't forget to add permissions to your manifest file if you're gonna be downloading stuff from the internet!
如果您要从 Internet 下载内容,请不要忘记为清单文件添加权限!
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<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>
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:debuggable="true">
</application>
</manifest>
回答by sheetal
Yes the code above will work .But if you are updating your progressbar
in onProgressUpdate
of Asynctask
and you press back button or finish your activity AsyncTask
looses its track with your UI .And when you go back to your activity, even if download is running in background you will see no update on progressbar. So on OnResume()
try to run a thread like runOnUIThread
with a timer task that updates ur progressbar
with values updating from the AsyncTask
running background.
是上面的代码将工作。但是,如果你正在更新progressbar
中onProgressUpdate
的Asynctask
,你按后退按钮或完成您的活动AsyncTask
失去其轨道与你的用户界面。而当你回到你的活动,即使下载在后台运行,你会看到进度条没有更新。因此,OnResume()
尝试运行一个线程,例如runOnUIThread
使用progressbar
从AsyncTask
运行后台更新的值来更新 ur 的计时器任务。
private void updateProgressBar(){
Runnable runnable = new updateProgress();
background = new Thread(runnable);
background.start();
}
public class updateProgress implements Runnable {
public void run() {
while(Thread.currentThread()==background)
//while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
Message msg = new Message();
progress = getProgressPercentage();
handler.sendMessage(msg);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
}
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
progress.setProgress(msg.what);
}
};
Don't forget to Destroythe thread when ur activity is not visible.
当您的活动不可见时,不要忘记销毁线程。
private void destroyRunningThreads() {
if (background != null) {
background.interrupt();
background=null;
}
}
回答by Raju yourPepe
My personal advice is to use Progress Dialogand build up before execution , or initiate at OnPreExecute()
, publish progress often if you use horizontal style of progress bar of the progress dialog. The remaining part is to optimize the algorithm of doInBackground
.
我个人的建议是使用Progress Dialog并在执行之前建立,或者OnPreExecute()
如果您使用进度对话框的进度条的水平样式,则经常在 处启动,发布进度。剩下的部分是优化算法doInBackground
。
回答by ENSATE
Do not forget to replace "/sdcard..." by new File("/mnt/sdcard/...") otherwise you will get a FileNotFoundException
不要忘记用新文件(“/mnt/sdcard/...”)替换“/sdcard...”,否则你会得到一个FileNotFoundException
回答by VinceStyling
回答by chintan adatiya
回答by Sandeep
While I was starting to learn android development, I had learnt that ProgressDialog
is the way to go. There is the setProgress
method of ProgressDialog
which can be invoked to update the progress level as the file gets downloaded.
当我开始学习 android 开发时,我知道这ProgressDialog
是要走的路。当文件被下载setProgress
时ProgressDialog
,可以调用其中的方法来更新进度级别。
The best I have seen in many apps is that they customize this progress dialog's attributes to give a better look and feel to the progress dialog than the stock version. Good to keeping the user engaged with some animation of like frog, elephant or cute cats/puppies. Any animation with in the progress dialog attracts users and they don't feel like being kept waiting for long.
我在许多应用程序中看到的最好的是,它们自定义了这个进度对话框的属性,使进度对话框的外观和感觉比股票版本更好。很好地让用户参与一些动画,如青蛙、大象或可爱的猫/小狗。进度对话框中的任何动画都会吸引用户,他们不想等待太久。
回答by Renetik
Use Android Query library, very cool indeed.You can change it to use ProgressDialog
as you see in other examples, this one will show progress view from your layout and hide it after completion.
使用 Android Query 库,确实很酷。您可以将其更改ProgressDialog
为在其他示例中看到的使用,这个将显示布局中的进度视图并在完成后隐藏它。
File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
public void callback(String url, File file, AjaxStatus status) {
if (file != null) {
// do something with file
}
}
});
回答by The Syrian
I have modified AsyncTask
class to handle creation of progressDialog
at the same context .I think following code will be more reusable.
(it can be called from any activity just pass context,target File,dialog message)
我已经修改了AsyncTask
类来处理progressDialog
在相同上下文中的创建。我认为以下代码将更可重用。(它可以从任何活动中调用,只需传递上下文、目标文件、对话框消息)
public static class DownloadTask extends AsyncTask<String, Integer, String> {
private ProgressDialog mPDialog;
private Context mContext;
private PowerManager.WakeLock mWakeLock;
private File mTargetFile;
//Constructor parameters :
// @context (current Activity)
// @targetFile (File object to write,it will be overwritten if exist)
// @dialogMessage (message of the ProgresDialog)
public DownloadTask(Context context,File targetFile,String dialogMessage) {
this.mContext = context;
this.mTargetFile = targetFile;
mPDialog = new ProgressDialog(context);
mPDialog.setMessage(dialogMessage);
mPDialog.setIndeterminate(true);
mPDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mPDialog.setCancelable(true);
// reference to instance to use inside listener
final DownloadTask me = this;
mPDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
me.cancel(true);
}
});
Log.i("DownloadTask","Constructor done");
}
@Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
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();
}
Log.i("DownloadTask","Response " + connection.getResponseCode());
// 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(mTargetFile,false);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
Log.i("DownloadTask","Cancelled");
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;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mPDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mPDialog.setIndeterminate(false);
mPDialog.setMax(100);
mPDialog.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
Log.i("DownloadTask", "Work Done! PostExecute");
mWakeLock.release();
mPDialog.dismiss();
if (result != null)
Toast.makeText(mContext,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(mContext,"File Downloaded", Toast.LENGTH_SHORT).show();
}
}