android - 在没有广播接收器的情况下从服务更新 ui

标签 android android-intentservice

在我的应用程序中,我使用了IntentService,并在其中调用了一个网络服务并解析我的响应。解析完成后我想更新 UI。

我看到有一种方法可以使用广播接收器来更新 UI,但是如果我不想使用广播接收器,还有其他方法可以更新 UI。如果是这样,请分享链接。

最佳答案

您可以创建一个绑定(bind)Service,或者使用一些像 EventBus 这样的库.

来自Android docs :

A bound service is the server in a client-server interface. A bound service allows components (such as activities) to bind to the service, send requests, receive responses, and even perform interprocess communication (IPC). A bound service typically lives only while it serves another application component and does not run in the background indefinitely.

如果您想使用此方法,则必须创建一个实现 onBind() 方法的 Service。此方法将返回您还必须实现的 IBinder。而且 Binder 将使用一个接口(interface),您必须再次创建该接口(interface)。

示例:

MyService.java

public class MyService extends Service {
    // ...
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder(this);
    }
}

MyBinder.java

public class MyBinder extends Binder {
    private MyServiceInterface mService;

    public MyBinder(MyServiceInterface s) {
        mService = s;
    }

    public MyServiceInterface getService() {
        return mService;
    }
}

MyServiceInterface.java

public interface MyServiceInterface {
    int someMethod();
    boolean otherMethod();
    Object yetAnotherMethod();
}

有关更多详细信息,您可以查看我上面链接的文档。

此方法的缺点:常规 Service 类不会像 IntentService 那样在后台运行。因此,您还必须实现一种在主线程之外运行事物的方法。


来自 EventBus page :

  • simplifies the communication between components
    • decouples event senders and receivers
    • performs well with Activities, Fragments, and background threads
    • avoids complex and error-prone dependencies and life cycle issues

要使用EventBus,最好的开始方式是按照the documentation开始.

因此,这两种方法似乎对您来说都是不错的选择,就像使用 BroadcastManager 一样(我不知道为什么您不能使用它)。

关于android - 在没有广播接收器的情况下从服务更新 ui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554068/

相关文章:

android - getString() 和 getResources.getString() 之间的区别

android - 多次调用 IntentService 的 startService 时 Intent 是否进入队列?

Android Oreo 服务限制会影响作业调度程序的 intentservices 吗?

java - 两个 Intent 服务是否会生成两个不同的工作线程?

android - 转换为新的 firebase - 枚举

android - 如何在没有 SuperSU 的情况下授予 root 访问权限

android - 从 IntentService 调用 AsyncTask 的问题

android - Android Manifest 文件中 Intent 过滤器的负优先级

java - Android 中的 HSVToColor 有点奇怪

android - ActivityNotFoundException 即使在 list 中声明之后