如果您正在异步工作,这意味着应用程序的其他部分不关心异步工作何时完成。
您通常想要做的是在异步工作完成时通知另一部分。为此,您需要使用“观察者模式”(文章包括流程图)。
基本思想是,您的应用程序启动异步工作并在工作完成时收到通知。这样,您可以松散地耦合应用程序的两个部分。一个简单的例子:
/**
* The observer
*/
public interface AsyncWorkDoneListener{
/**
* This method will be called when the async-thread is
* done.
*/
public void done(Object unit);
}
/**
* The worker (which does the asyc-work on another thread).
*/
public class AsyncWorker{
private AsyncWorkDoneListener listener;
/**
* Set (you might want to maintain a list here) the current
* listener for this "AsyncWorker".
*/
public void setListener(AsyncWorkDoneListener listener){
this.listener = listener;
}
/**
* Will do the async-work
*/
public void doWork(){
// Do the work in another thread...
// When done, notify the registered listener with the
// result of the async work:
this.listener.done(the_object_containing_the_result);
}
}
/**
* The application
*/
public class App implements AsyncWorkDoneListener{
public void someMethod(){
// Work on something asynchronously:
mAsyncWorker.setListener(this);
mAsyncWorker.doWork();
}
@Override
public void done(Object unit){
// The asyc work has finished, do something with
// the result in "unit".
}
}