简体   繁体   English

Android / Java中的网络-从服务器回调后如何回调到API类?

[英]Networking in Android/Java - how do I callback to a API class after a call back from the server?

So I'm writing an Android application in Java based on an iOS application that I am also working on, but this question is more asking about how to communicate callback mechanism (like blocks in Objective-C 2.0) in Java. 因此,我正在基于正在开发的iOS应用程序中用Java编写一个Android应用程序,但是这个问题更多的是关于如何在Java中传达回调机制(例如Objective-C 2.0中的块)。

This application involves networking, authenticating and communicating with a server via an API. 该应用程序涉及通过API联网,认证服务器并与服务器通信。

I am using this framework: https://github.com/loopj/android-async-http 我正在使用这个框架: https : //github.com/loopj/android-async-http

I am trying to encapsulate all of the networking model into classes to make everything clean and easy (it seems so easy in iOS with delegates and blocks, but java doesn't appear to have ANY of these conveniences). 我正在尝试将所有网络模型封装到类中,以使所有内容都变得简洁明了(在带有委托和块的iOS中看起来是如此简单,但是java似乎没有这些便利)。 So, I am using this as a guide for callbacks: http://www.gdgankara.org/2013/03/25/android-asynchronous-http-client-a-callback-based-http-client-library-for-android-and-android-smart-image-view/ 因此,我以此为指导进行回调: http : //www.gdgankara.org/2013/03/25/android-asynchronous-http-client-a-callback-based-http-client-library-for-机器人和- Android的智能图像的视图/

Now lets say I don't want to make a call from an Activity class, but an API class, which can be called from an Activity class, how can I do this? 现在让我们说我不想从Activity类进行调用,但是不想从Activity类进行调用的API类,该如何做呢? I know easily how to do this with blocks and delegates in iOS, but how can I do this with interfaces? 我很容易知道如何使用iOS中的块和委托来执行此操作,但是如何使用接口来执行此操作呢?


For Example: 例如:

In iOS (using a common networking framework called AFNetworking), I have 4 classes: iOS中 (使用称为AFNetworking的通用网络框架),我有4个类:

HTTPClient.h/m HTTPClient.h /米

+(id)sharedHTTPClient
  {
    static dispatch_once_t pred = 0;
    __strong static id __httpClient = nil;
    dispatch_once(&pred, ^{
        NSString *baseURL = http://baseurl.com;
        __httpClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
        [__httpClient setParameterEncoding:AFJSONParameterEncoding];        

    });
    return __httpClient;
}

APILogin.h/m APILogin.h /米

-(void)loginWithSuccessBlock:(void (^)(NSArray *responseArray))loginSuccess {
    HTTPClient *httpClient = [HTTPClient sharedHTTPClient];
    NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:@"/api/login" parameters:nil];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *response = [self.jsonParser parseResponseFromJSON:JSON];
        if (loginSuccess) {
            loginSuccess(response);
        }

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {  
        [APIErrorHandler handleError:error withHTTPResponse:response];
    }];

    [operation start];
}

LoginObject.h/m LoginObject.h /米

-(id)init
 {
     self = [super init];
     if(self) {
         [self.apiLogin loginWithSuccessBlock:^ void (NSArray *loginArray) {
                //process the array
          }];
     }
 }

LoginVC.h/m LoginVC.h /米

...
LoginObject *loginObj = [[LoginObject alloc] init];
...

So, now what I have so far, using the Android-Async-Http library is: 因此,到目前为止,到目前为止,使用Android-Async-Http库的内容是:

HTTPClient.java HTTPClient.java

public class HTTPClient extends AsyncHttpClient {
    public static HTTPClient sharedHTTPClient;
    public static String baseUrl = "http://baseurl.com";
    public HTTPClient {
        super();
    }
    ...
}

APILogin.java APILogin.java

public class APILogin {
    public void loginWithSuccessBlock() {
        HTTPClient httpClient = QHTTPClient.sharedHTTPClient;
    httpClient.get("/api/login", new JsonHttpResponseHandler() {
         @Override
         public void onSuccess(JSONArray response) {
             // Successfully got a response
            ArrayList<LoginObject> loginInfo = this.jsonParser.parseLoginFromJSON(response);
            **NEED TO DO A CALL BACK!! Like with the blocks in iOS**
         }
        @Override
         public void onSuccess(JSONObject response) {
             // Successfully got a response
            // shouldn't be an object
            throw new IllegalArgumentException();
         }


         @Override
         public void onFailure(Throwable e, String response) {
             // Response failed :(
         }
    });
}

LoginObject.java LoginObject.java

public class LoginObject {
    public LoginObject {
        this.apiLogin.loginWithSuccessBlock(**something something for a callback**);
    }
}

Hopefully, I've made it a little clearer what I am trying to achieve. 希望我已经弄清楚了我要实现的目标。 I want to be able to execute some kind of callback block on the object that called the api call, on success. 我希望能够在成功调用api调用的对象上执行某种回调块。 However, it will not always be the same object. 但是,它并不总是同一对象。 LoginObject may have an instance of APILogin.java and so might a different object, so I can't use the second link above in which you can specific a specific class and pass it in and call a method on it, because the classes will be of different types, and Java doesn't have a generic pointer (id or void*) object. LoginObject可能具有APILogin.java的实例,因此可能具有不同的对象,因此我无法使用上面的第二个链接,在该链接中您可以指定特定的类并将其传递并在其上调用方法,因为这些类将是具有不同类型,并且Java没有通用指针(id或void *)对象。

So I've discovered my own answer after trying many things and scouring the web for a possible solution. 因此,在尝试了许多事情并在网上搜寻可能的解决方案之后,我找到了自己的答案。 What I've come up with is to basically chain the response handlers. 我想出的基本上是将响应处理程序链接起来。

So for: 因此对于:

public class APILogin {
    public void loginWithSuccessBlock(**final JsonHttpResponseHandler handler**) {
        HTTPClient httpClient = QHTTPClient.sharedHTTPClient;
        httpClient.get("/api/login", handler);
    }
}

public class LoginObject {
    public LoginObject {
        this.apiLogin.loginWithSuccessBlock(new JsonHttpResponseHandler(){
        ...
        );
    }
}

which isn't very robust because it doesn't let me do much customization, but it'll do. 这不是很可靠,因为它不能让我做太多自定义操作,但是可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM