My project is where, i have to w开发者_开发百科ait, for a background operation to get completed. Till then, a progress dialog is shown. Now, after the operation is done, the results are stored in a List and a list should be created.
Everything seems to be working fine ( the progress dialog and all), but in wait(), my code (seen in stack overflow) is
Runnable runnable = new Runnable() {
public void run() {
// wait(); This call wouldn't work
synchronized (this) {
wait(); // This call will work
}
}
};
and after the background operation is completed, it is
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
System.out.println("Doneee!!! Yup yes ");
pd.dismiss();
synchronized (runnable) {
runnable.notifyAll(); // this call will work
}
}
But the problem is, the wait is getting hanged up. I mean, when i tried to debug also, the wait() doesn't return. It's in waiting state only. So can you please help me out to do it!
Thanks a lot in advance!
Regards Nithin
If you are displaying a progress dialog, then; hopefully, you are sending progress notification from the background process to the progress dialog, so that the "progress dialog" is not a "I am a goofball so I will not actually show the progress" dialog. Have the background process send a "I am done" notifiction.
Waits need to be synchronized in order to avoid exactly the problem you're seeing. The solution to your problem is to use a flag as well as a wait() and notify() call. Synchronization to wait for an operation to finish should look something like this:
boolean done = false;
...
synchronized(this) {
if (!done) wait();
}
...
synchronized(this) {
done = true;
notifyAll();
}
If you don't have the flag, then it's possible for notifyAll() to be called before wait() is, at which point you end up waiting forever. The synchronized blocks are required to make sure the notify doesn't happen between you checking done and calling wait(). The reason Java objects if they aren't present is because the language designers are trying to subtly remind you that this kind of system is usually necessary.
Edited to add: In Android, for most purposes, the AsyncTask class takes all the hassle out of doing this kind of thing. Use it whenever possible.
精彩评论