I need to download an image in an ImageView
. I want to use a ProgressBar
to tell the user that the program is downloading images. If the program can't download the image in 30sec, the program will use a Toast
/AlertDialog
to notify the user and exit.
How can I implement this function? Could anyone give me some advice on how to build the framework? I can complete the details. Do I need thread? / AsyncTask?
Yes, you do need to download the image in AsyncTask (I am assuming that you are downloading from URL).
Effectively to achieve your functionality this is what you need to do:
- Create AsyncTask to download your image (implement download in doInBackground()), also have a boolean (say isImageDownloaded) to track if the image is successfully downloaded in postExecute(). Don't forget to also show your progress bar before initiating the download
- Execute your AsyncTask to initiate download
- Create extension of android.os.CountDownTimer to countdown 30 secs
- On the method onFinish() check the boolean that you track, if it is false then you cancel the AsyncTask and throw the toast/dialog that you intended
Below is the pseudocode/skeleton of what the steps that I mentioned above (didn't check for syntax, so I apologize for any error)
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()
}
Maybe this helps a little bit.
The code for the progress bar you can find here.
You could also see this. It will cover the process of downloading the image to the phone as well as providing loading threads while the image is being downloaded.
I hope you are trying to download an image from a known url, am i right? If so please have a look at this url
Hope that helps you...