等待函数完成执行并使用结果
场景
这是我有一个活动(A)的 ,它有一个按钮和文本视图。我有另一个类(B),其中包含执行各种功能的方法。创建类 B 的实例后,当单击按钮时,会从 A 调用它的公共方法之一。该方法需要一段时间才能执行(它调用类中另一个耗时的私有方法)并返回类 B 的一个私有成员的值。
问题在于该方法返回该成员的初始值而不是值计算后。有没有办法强制函数等待一段时间并返回计算成员的值?
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
}
返回的值始终是 mItem 的默认值,即构造函数中设置的值。 startFunction(WiFi 扫描) 所花费的时间是任意的。任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建类 B 的实例时,请确保它将 Context 作为其构造函数中的参数。然后你可以尝试使用
AsyncTask
(假设你知道)。然后将耗时的函数放在doInBackground()
中,将等待其值的函数放在onPostExecute()
中When you create an instance of class B make sure it takes
Context
as an argument in its constructor. Then you can try usingAsyncTask
(Assuming you know it). Then put the time consuming function indoInBackground()
and the function which waits for its values inonPostExecute()
Android 开发是事件驱动的,您通常不应该阻塞等待结果的线程(至少不应该阻塞主/ui 线程,因为您的应用程序可能会被视为没有响应)。
最好创建一个回调接口,让执行时间较长的方法在计算完成后调用该接口上的方法。
顺便说一句,你的帖子表明计算已经是异步的?否则,您将在该方法完成后得到结果。
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.