从服务到活动传信息的最佳实践(或片段) [英] Best practice for pass info from Service to Activity (or Fragment)

查看:289
本文介绍了从服务到活动传信息的最佳实践(或片段)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的的Andr​​oid 应用一个 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);
}

添加设置监听器法服务活动

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆