【发布时间】:2016-02-22 12:45:20
【问题描述】:
在我的应用程序中,我使用了IntentService,并在其中调用了一个网络服务并解析我的响应。解析完成后,我想更新 UI。
我看到有一种方法可以使用广播接收器更新 UI,但是如果我不想使用广播接收器,还有其他方法可以更新 UI。如果是,请分享链接。
【问题讨论】:
标签: android android-intentservice
在我的应用程序中,我使用了IntentService,并在其中调用了一个网络服务并解析我的响应。解析完成后,我想更新 UI。
我看到有一种方法可以使用广播接收器更新 UI,但是如果我不想使用广播接收器,还有其他方法可以更新 UI。如果是,请分享链接。
【问题讨论】:
标签: android android-intentservice
你可以绑定Service,或者使用像EventBus这样的库。
来自Android docs:
绑定服务是客户端-服务器接口中的服务器。有界 服务允许组件(例如活动)绑定到服务, 发送请求,接收响应,甚至执行进程间 通信(IPC)。绑定服务通常只存在于它 服务于另一个应用程序组件并且不在 背景无限期。
如果您想使用这种方法,您必须创建一个实现onBind() 方法的Service。此方法将返回您还必须实现的IBinder。 Binder 将使用 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,最好的开始方式是关注the documentation。
所以,这两种方法中的任何一种对你来说似乎都是一个不错的选择,就像使用 BroadcastManager 一样(我不知道你为什么不能使用它)。
【讨论】: