android - 如何在android中实现 block

标签 android ios android-asynctask block

在 IOS 中,当我们想要在特定情况发生时处理一个 Action 时,我们使用 block

Android 中是否有这样的方法来处理 onCompletion 情况,我们可以在任何地方添加。

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

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

BaseAsyncTask(new Callback(){

onPostResult(string result)
{
// do whatever you want to do with the result got from asynctaks
}
});

它是一个委托(delegate),它会在遇到特定情况时调用..

上面的代码是 android 中的 block ,就像我们在 IOS 中所做的那样,我说得对吗?或者有任何其他方式在 android 中创建 block 。

最佳答案

表现得像 iOS block :

一个。比方说,在你的类 APISingleton 中(例如单例类中的 Volley request-API):

  1. 在类外定义接口(interface):

    // Callback Blueprint  
    interface APICallback {
        void onResponse(User user, boolean success, String message); // Params are self-defined and added to suit your needs.
    }
    
  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");  
    }
    

B.因此,如何调用 API 请求并从您的 Activity 或 fragment 传递回调函数,如下所示:

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
        }
    });

关于android - 如何在android中实现 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115711/

相关文章:

android - 如何通过我的耳机播放 DTMF 音调?

ios - 为 Titanium Appcelerator 项目在 Apple Developer 上注册新设备

ruby-on-rails - 核心数据 : import a tree structure with find or insert/duplicate entries

Android:将字符串传递给 asyncTask

java - 如何实例化AsyncTask

android - mayInterruptIfRunning取消ASyncTask的用法-函数调用顺序-

android - 具有动态功能的即时应用程序始终显示带有 1 个选项的消歧对话框

java - 在 Kotlin/Android 中的 WebView 中搜索字符串

android - 如何在 SQLite 中以古吉拉特语存储数据?

ios - 如何从 URL 中拆分出现 "users/"的字符串?