android - 从 OkHttp 拦截器通知 UI

标签 android okhttp interceptor

我需要根据拦截器中的 bool 值更改UI(我只在拦截器内部知道它并且它永远不会离开它)。

我想到的可能解决方案:
创建像 new Handler(Looper.getMainLooper()) 这样的处理程序,然后执行 .post(new Runnable()..),但我不想弄乱 UI 逻辑进入拦截器类。

最佳答案

您可以尝试使用EventBus .

  1. 将以下依赖项添加到您的 build.gradle 文件中:
dependencies {
    // ...
    implementation 'org.greenrobot:eventbus:3.1.1'
}
  • 创建用于保存来自拦截器的数据的类:
  • public static class InterceptorEvent { /* Add fields you need */ }
    
  • 在您的拦截器中,使用以下代码发布事件:
  • EventBus.getDefault().post(new InterceptorEvent());
    
  • 根据需要订阅 InterceptorEvent:
  • @Subscribe(threadMode = ThreadMode.MAIN)  
    public void onInterceptorEvent(InterceptorEvent event) {
        // Do whatever you want
    }
    
    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
    
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    

    希望我的回答有帮助。

    关于android - 从 OkHttp 拦截器通知 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957217/

    相关文章:

    android - 使用android低级api解码H264流

    android - 读取失败 : EBADF (Bad file descriptor) while reading from InputStream Nougat

    android - 为什么 Volley Library 通常与 okHttp Library 结合使用?

    java - 在 ContainerRequestFilter 中获取资源类注释值

    android - 在 gradle 中重命名类

    android - 对话框上的后退按钮正在取消对话框,即使我有一个监听器

    java - Android Studio Spinner 导致应用程序在打开之前崩溃

    java - OkHttpClient 获取响应正文

    unit-testing - Nock拦截请求但返回空对象

    ioc-container - Ninject:为 AoP 代理类型时可以使用注入(inject)构造函数吗?