2011-08-19 70 views
1

我需要下载ImageView中的图像。我想使用ProgressBar来告诉用户程序正在下载图像。如果程序无法在30秒内下载图像,程序将使用Toast/AlertDialog来通知用户并退出。在Android ImageView和Progressbar实现中下载图像

我该如何实现这个功能?任何人都可以给我一些关于如何构建框架的建议吗?我可以完成细节。我需要线程吗?/AsyncTask?

回答

0

我希望你试图从一个已知的网址下载图片,我是对吗?如果是这样,请有look at this url

希望帮助你...

0

也许this有助于一点点。

进度条的代码,你可以找到here

0

您还可以看到this。它将涵盖将图像下载到手机的过程,以及在下载图像时提供加载线程的过程。

1

是的,你需要下载AsyncTask中的图像(我假设你是从URL下载的)。 有效地实现你的功能,这就是你需要做的:

  1. 创建的AsyncTask下载图像(实现doInBackground()下载),也有一个布尔值(比如isImageDownloaded)来跟踪影像是否成功在postExecute()中下载。不要忘了启动下载之前还显示进度条
  2. 执行您的AsyncTask启动下载
  3. 创建扩展android.os.CountDownTimer的读秒30秒
  4. 在方法onFinish()检查布尔你跟踪,如果是假的,那么你取消的AsyncTask扔你打算

下面是什么我上面提到的(没有检查语法步骤的伪代码/骨架的面包/对话框,所以我很抱歉有任何错误)



    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() 
     }