[英]How to return value from anonymous class?
我有以下代码。
正如您所看到的, postTestResults
方法应该返回一个布尔值。
现在的问题是在postTestResults
我创建了一个内部类AsyncHttpResponseHandler
,我重写了onSuccess
和onFailure
来获取AsyncHttpResponseHandler的结果。
但是如果我在onSuccess
和onFailure
返回true ,显然它不起作用,因为onSuccess
和onFailure
必须返回void 。
请问我该如何应对这种情况?
public static Boolean postTestResults(DBManager db, String mDeviceId,
String mFirmwareVer, String mJobNo, int mTestType, Activity activity) {
MyRestClient.post(possibleEmail, device, results, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
return true; // does not work!
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
// TODO Auto-generated method stub
}
});
return null;
}
谢谢
在调用MyRestClient.post
,仍然没有可用的信息。 在将来的某个时间onSuccess或onFailure被调用。 这种异步行为是有意的,因为否则你将不得不等待通信旅行。
不要归还任何东西,或者也许是真的。 完全不同的处理,通过调用onSuccess / onFailure中的内容来处理逻辑。
您可以强制等待结果(绝对可怕):
final Semaphore semaphore = new Semaphore(0);
final AtomicBoolean succeeded = new AtomicBoolean();
MyRestClient.post(possibleEmail, device, results, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
succeeded.set(true);
semaphore.release();
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
succeeded.set(false);
semaphore.release();
}
});
semaphore.aquire();
return succeeded.get();
调用发布后,信号量将暂停当前线程的执行(因为其构造函数中有0个许可)。 当回调完成时(onSuccess / onFailure),结果被设置(成功)。
局部变量必须(有效)最终,因此它们的对象不会改变。 这是因为回调在另一个线程中,并且回调中引用的对象是实际副本 。 所以要理解必须是最终的。 但是必须写入结果,因此必须使用值保持器,最终对象的内部状态。 因此,无法写入作为final boolean
的AtomicBoolean。
顺便说一句, Boolean
作为结果如果一个对象包装器(Boolean.TRUE,FALSE或null), boolean
似乎更合适。
在您的代码示例中,您使用的是匿名类而不是内部。
匿名类与常规类没有区别。 它是一个语法糖,允许您实现接口(不声明类名称,javac将为您执行此操作)。
在您的情况下,您应该通过中断代码的执行在方法onFailure
命令中抛出异常。
因为你处理异步调用,你不知道什么时候会执行代码。 因此,应该从onSuccess
方法调用您要成功执行的任务,或者应用程序应该在某个地方等待回调的结果。
你可以添加这样的系统:
public class MyAsync extends AsyncHttpResponseHandler{
private final MyAsyncState state;
public MyAsync(MyAsyncState state){
this.state = state;
}
public void onSuccess(......){
this.state.setResult(true);
}
public void onFailure(.....){
this.state.setResult(false);
}
}
MyAsyncState类:
public class MyAsyncState{
private Boolean state;
public void setResult(boolean b){
this.state = b;
doIt();
}
private void doIt(){
// do what you want
// show popup for example
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.