如何在android中实现块

Xar*_*mer 1 android block ios android-asynctask

In IOS we use blocks when we want to handle an action when a particular situation occur.

在android中有没有这样的方法来处理onCompletion的情况,我们可以添加它在哪里.

AsyncTask方法一样,它知道工作何时完成.它执行onPostExecute.当特定情况到达时我们如何创建这种类型的方法,我们就像处理它一样.

今天我找到了一种在IOS中表现得像Block的方式

BaseAsyncTask(new Callback(){

onPostResult(string result)
{
// do whatever you want to do with the result got from asynctaks
}
});
Run Code Online (Sandbox Code Playgroud)

它是一个委托,它在达到特定情况时调用..

我是正确的,上面的代码是我们在IOS中的块中的块.或者在android中有任何其他创建块的方法.

fel*_*wcf 9

像iOS Block一样:

.比方说,在你的班级APISingleton中(例如,在单件类中的Volley request-API):

  1. 定义类外的接口:

    // Callback Blueprint  
    interface APICallback {
        void onResponse(User user, boolean success, String message); // Params are self-defined and added to suit your needs.
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在您的API请求函数中

    public void requestAPIWithURL:(String url, final APICallback callback) {
        // ....
        // After you receive your volley response,
        // Parse the JSON into your model, e.g User model.
        callback.onResponse(user, true, "aloha");  
    }
    
    Run Code Online (Sandbox Code Playgroud)

B.那么,如何调用API请求并从您的活动或片段中传递回调函数,如下所示:

APISingleton.getInstance().requestAPIWithURL("http://yourApiUrl.com", new APICallback() {
        @Override
        public void onResponse(User user, boolean success, String message) {
            // you will get your user model, true, and "aloha" here
            mUser = user;
            Log.v(TAG, "success:" + success);
            Log.v(TAG, "aloha or die?" + message);

            // Your adapter work. :D
        }
    });
Run Code Online (Sandbox Code Playgroud)