将信息从服务传递到活动(或片段)的最佳实践 [英] Best practice for pass info from Service to Activity (or Fragment)
问题描述
我在我的 Android
应用程序上运行一个 Socket.IO
客户端,但我无法从 Service
(处理套接字的连接)到 Fragments
之一.
I am running a Socket.IO
client on my Android
app and I am having trouble passing data from the Service
(that handles the connection of the socket) to one of the Fragments
.
在我的一个 Activity
中,我打开了一个包含个人资料页面的片段.当配置文件片段打开时,我会向服务器发出一个请求配置文件信息的事件.
In one of my Activities
, I open up a fragment that has a profile page. When the profile fragment opens, I emit an event to the server asking for the profile information.
我从服务器获取信息没有问题,但我无法将该数据(JSON 字符串)发送到当前片段.
I am getting the information back from the server with no problems, but I am having trouble sending that data (a JSON string) to the current fragment.
将此信息从 Service
传递到 Fragment
(或 Activity
)的最佳做法是什么?
What would be the best practice to pass this information from the Service
to the Fragment
(or the Activity
)?
谢谢!
推荐答案
您可以从 Activity
bind
到 service
并创建一个<代码>服务连接代码>.这样你就有service
的instance
进行通信.
You can bind
to the service
from Activity
and create a service connection
. So that you will have the instance
of service
to communicate.
在这里查看我的回答 如何通过从活动到服务的处理程序 关于如何绑定到服务并建立服务连接.
See my answer here How to pass a handler from activity to service on how to bind to service and establish a service connection.
除此之外,在您的服务中定义一个interface
Apart from this, have an interface
defined in your service
public interface OnServiceListener{
public void onDataReceived(String data);
}
在service
中添加一个set Listener
方法,从Activity
private OnServiceListener mOnServiceListener = null;
public void setOnServiceListener(OnServiceListener serviceListener){
mOnServiceListener = serviceListener;
}
接下来,在你的Activity中实现监听器接口
Next, In your Activity implement the Listener interface
公共类 MainActivity 扩展了 ActionBarActivity实现 CustomService.OnServiceListener{
public class MainActivity extends ActionBarActivity implements CustomService.OnServiceListener{
@Override
public void onDataReceived(String data) {
}
}
接下来,服务连接建立后,注册监听器
Next, When the service connection is established , register the listener
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
customService = ((CustomService.LocalBinder) iBinder).getInstance();
customService.setOnServiceListener(MainActivity.this);
}
现在,当您在服务中接收到数据时,通过onDataReceived
方法将数据传递给 Activity.
Now, When you receive the data in service pass the data to the Activity through onDataReceived
method.
if(mOnServiceListener != null){
mOnServiceListener.onDataReceived("your data");
}
这篇关于将信息从服务传递到活动(或片段)的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!