问题
Here's the scenario
I have an activity(A) which has a button and textview. I have another class(B) with methods for performing various functions. After creating an instance of class B, one of it's public method is called from A when the button is clicked. The method takes a while to execute(it invokes another time consuming private methods in the class) and returns the value of one of the private members of class B.
The trouble is that the method returns the initial value of the member and not the values after computation. Is there way to force the function to wait for some time and return the value of member of computation?
public String getItem(){
startFunction(); //Time consuming Function
generateItem(); //Function which uses results of startFunction() to generate item and set values to mItem
return mItem; //mItem is the private member of class B
}
The value returned always is the default value of mItem i.e value set in the constructor. The time taken by startFunction(WiFi Scanning) is arbitrary. Any help would be much appreciated.
回答1:
When you create an instance of class B make sure it takes Context
as an argument in its constructor. Then you can try using AsyncTask
(Assuming you know it). Then put the time consuming function in doInBackground()
and the function which waits for its values in onPostExecute()
回答2:
Android development is event driven, you should normally not block threads waiting for a result (at least not the main/ui thread since your application then might be considered as not responding).
It's better to create a callback interface, and let the metod that takes a long time to execute, invoke a method on that inteface when the computation has been completed.
Btw, your post indicates that the computation already is asynchronous? You would otherwise have the result when the method has completed.
来源:https://stackoverflow.com/questions/6760829/waiting-for-a-function-to-finish-execution-and-using-the-results