Firstly, I would suggest that if the user clicked on something, he should see some immediate result, in your case, if the button action should wait for something, add a circle loading animation to the button to immediately tell the user the action will happen soon.
Now for the action itself, if there is only one (or several) of such possible actions that occur after one (or several) possible background processes, I would add a button to raise the flag synchronously (possibly through a constant member of the class) and execute a lengthy process synchronously , to check this flag after completion of the process and perform the requested action at completion.
Another possible option, if you use wait and notify so that the button code waits for the process to complete, is usually considered a very high-performance solution in Java:
for example (ignore typos, this is in place):
button.setOnClickListener(new OnClickListener() { public void onClick(View v) { v.post(new Runnable() { @Override public void run() { synchronized (lockObject) { try { lockObject.wait(); doAction(); } catch (InterruptedException e) {} } } } } }
Then complete the notify
process when it finishes.
Note that new Runnable()
does not create a new thread, it just adds Runnable
to the View
thread queue
As suggested by the mice, the onClick button handler should check if the process is currently running, and if it is so simple to immediately execute the action.
This way you do not need to create a new thread (or AsyncTask, which is actually a thread pool)
source share