从服务到活动传信息的最佳实践(或片段) [英] Best practice for pass info from Service to Activity (or Fragment)
问题描述
我正在我的的Android
应用一个 Socket.IO
客户端和我有麻烦从传递数据服务
(处理插座的连接)与片段中的一个
。
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
.
在我的活动有一个
,我打开具有配置页面片段。当轮廓片段打开时,我发出一个事件到服务器要求的配置文件信息。
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.
什么是最好的做法来传递这一信息服务
到片段
(或活动
)?
What would be the best practice to pass this information from the Service
to the Fragment
(or the Activity
)?
感谢您!
推荐答案
可以绑定
到服务
从活动
并创建一个服务连接
。所以,你将有服务
的实例
沟通。
You can bind
to the service
from Activity
and create a service connection
. So that you will have the instance
of service
to communicate.
请参阅我的答案在这里<一个href=\"http://stackoverflow.com/questions/22573301/how-to-pass-a-handler-from-activity-to-service/22573715#22573715\">How从活动传递一个处理程序服务如何绑定到服务,建立服务连接的 的
See my answer here How to pass a handler from activity to service on how to bind to service and establish a service connection.
除此之外,有的接口服务定义的
Apart from this, have an interface
defined in your service
public interface OnServiceListener{
public void onDataReceived(String data);
}
在添加
从设置监听器
法服务活动注册监听器code>
private OnServiceListener mOnServiceListener = null;
public void setOnServiceListener(OnServiceListener serviceListener){
mOnServiceListener = serviceListener;
}
接下来,在你的活动实现了Listener接口
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
方法传递数据的活动。
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屋!