Threads and ProgressDialog
I am developing my first Androïd application and I'm facing a problem when I want to display a ProgressDialog to indicate that a process is being run. In my application, the user triggers a time consuming t开发者_运维百科ask by pressing a Button. The "OnClick" function of my "OnClickListener" is called when the user presses the Button. In this function, here is what I'm currently doing :
- creation and configuration of an instance of the ProgressDialog class,
- creation of a thread dedicated to the time consuming task,
- attempt to display the ProgressDialog using the "show" method,
- start of the thread,
- main Activity suspended (call of the "wait" function)
- wake up of the main Activity by the thread when it is finished
- removal of the ProgressDialog by calling the "dismiss" function.
Everything works fine (the result of the long task is correct) but the ProgressDialog nevers appears. What am I doing wrong?
Thanks in advance for the time you will spend trying to help me.
You should not call wait()
to the Main Activity/UI thread, because this is actually freezing the UI including your ProgressDialog, so it has no time to fade in and will never be shown.
Try to use multithreading correctly: http://developer.android.com/resources/articles/painless-threading.html
final Handler transThreadHandler = new Handler();
public void onClick(View v) {
// show ProgressDialog...
new Thread(){
public void run(){
// your second thread
doLargeStuffHere();
transThreadHandler.post(new Runnable(){public void run(){
// back in UI thread
// close ProgressDialog...
}});
}
}.start();
}
I would suggest using AsyncTask
, as it's purpose is exactly to handle this kind of problem. See here for instructions how to use it. Note that the linked page in Floern's answer also recommends the use of AsyncTask
.
You would need to do the following:
- subclass
AsyncTask
- override it's
onPreExecute()
method to create and show aProgressDialog
. (You could hold a reference to it in a member of your subclass) - override it's
doInBackground()
method to execute your time consuming action. - override it's
onPostExecute()
method to hide your dialog. - in your activity, create an instance of your subclass and call
execute()
on it.
If you make your subclass an inner class of your activity, you can even use all of your activity's members.
精彩评论