【问题标题】:Image download in an Android ImageView and Progressbar implementationAndroid ImageView 和 Progressbar 实现中的图像下载
【发布时间】:2011-08-19 17:55:27
【问题描述】:
我需要下载ImageView 中的图像。我想使用ProgressBar 告诉用户程序正在下载图像。如果程序在 30 秒内无法下载图片,程序将使用Toast/AlertDialog 通知用户并退出。
如何实现这个功能?谁能给我一些关于如何构建框架的建议?我可以完成细节。我需要线程吗? /异步任务?
【问题讨论】:
标签:
android
frameworks
download
progress-bar
android-imageview
【解决方案1】:
是的,您确实需要在 AsyncTask 中下载图像(我假设您是从 URL 下载的)。
要有效地实现您的功能,您需要这样做:
- 创建 AsyncTask 以下载您的图像(在 doInBackground() 中实现下载),还有一个布尔值(例如 isImageDownloaded)来跟踪图像是否在 postExecute() 中成功下载。在开始下载之前不要忘记显示您的进度条
- 执行您的 AsyncTask 以启动下载
- 创建 android.os.CountDownTimer 的扩展以倒计时 30 秒
- 在 onFinish() 方法上检查您跟踪的布尔值,如果它为 false,则取消 AsyncTask 并抛出您想要的 toast/对话框
下面是我上面提到的步骤的伪代码/骨架(没有检查语法,所以我为任何错误道歉)
public void downloadAndCheck() {
AsyncTask downloadImageAsyncTask =
new AsyncTask() {
@Override
protected Boolean doInBackground(Void... params) {
// download image here, indicate success in the return boolean
}
@Override
protected void onPostExecute(Boolean isConnected) {
// set the boolean result in a variable
// remove the progress bar
}
};
try {
downloadImageAsyncTask.execute();
} catch(RejectedExecutionException e) {
// might happen, in this case, you need to also throw the alert
// because the download might fail
}
// note that you could also use other timer related class in Android aside from this CountDownTimer, I prefer this class because I could do something on every interval basis
// tick every 10 secs (or what you think is necessary)
CountDownTimer timer = new CountDownTimer(30000, 10000) {
@Override
public void onFinish() {
// check the boolean, if it is false, throw toast/dialog
}
@Override
public void onTick(long millisUntilFinished) {
// you could alternatively update anything you want every tick of the interval that you specified
}
};
timer.start()
}
【解决方案3】:
您还可以看到this。它将涵盖将图像下载到手机的过程以及在下载图像时提供加载线程。