4 回答
TA贡献1865条经验 获得超7个赞
** 这对我有用 **
@NonNull
@Override
public Result doWork() {
final Result[] result = new Result[1];
mUpLoadDataService.uploadInspectionData(new UpLoadDataService.UploadCompleteListener() {
@Override
public void uploadComplete() {
result[0] = Result.success(); //this is what I want to do
}
@Override
public void uploadFailed(String reason) {
result[0] = Result.failure(); //this is what I want to do
}
});
return result[0];
}
TA贡献1770条经验 获得超3个赞
public Result doWork(UpLoadDataService.UploadCompleteListener uploadListener) {
mUpLoadDataService.uploadInspectionData(uploadListener);
return null;
}
现在传递父函数的实现。假设你的父函数被命名为foobar
void foobar() {
someObject.doWork(new UpLoadDataService.UploadCompleteListener() {
@Override
public void uploadComplete() {
//write your logic here
return Result.success();
}
@Override
public void uploadFailed(String reason) {
//write your logic here
return Result.failure();
}
});
}
TA贡献1890条经验 获得超9个赞
您可以使用以下方式获取任务的回调
doWork(paremter, new ServiceListener<String>() { //paremter if any
@Override
public void success(String obj) {
//get the response if success
}
@Override
public void fail(ServiceError error) {
//get the error response
}
});
完成工作并从调用的地方发送调用响应
private void doWork(String param , ServiceListener<String> serviceListener) {
mUpLoadDataService.uploadInspectionData(new UpLoadDataService.UploadCompleteListener() {
@Override
public void uploadComplete() {
serviceListener.success("success");
}
@Override
public void uploadFailed(String reason) {
serviceListener.fail(new ServiceError("Can not Upload"));
}
});
}
ServiceListener接口定义如下
public interface ServiceListener<T> {
void success(T obj);
void fail(ServiceError error);
}
public class ServiceError {
public Throwable errorObject;
public String message;
public ServiceError(){
message = "";
}
public ServiceError(String message){
this.message = message;
}
public ServiceError(String message, Throwable errorObject){
this.message = message;
this.errorObject = errorObject;
}
public Object getErrorObject() {
return errorObject;
}
public void setErrorObject(Throwable errorObject) {
this.errorObject = errorObject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
TA贡献1820条经验 获得超2个赞
您可以EventBus在您想要的每个地方使用通知订阅方法,如下所示:
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
public void doWork() {
mUpLoadDataService.uploadInspectionData(new UpLoadDataService.UploadCompleteListener() {
@Override
public void uploadComplete() {
EventBus.getDefault().post(new MessageEvent("success"));
}
@Override
public void uploadFailed(String reason) {
EventBus.getDefault().post(new MessageEvent("failed"));
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}
请参阅本实施指南。
添加回答
举报