Best practice for pass info from Service to Activity (or Fragment)

不羁的心 提交于 2019-11-30 16:13:48

问题


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.

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)?

Thank you!


回答1:


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.

Apart from this, have an interface defined in your service

public interface OnServiceListener{
    public void onDataReceived(String data);
}

Add a set Listener method in service to register the listener from Activity

private OnServiceListener mOnServiceListener = null;

public void setOnServiceListener(OnServiceListener serviceListener){
    mOnServiceListener = serviceListener;
}

Next, In your Activity implement the Listener interface

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);
    }

Now, When you receive the data in service pass the data to the Activity through onDataReceived method.

if(mOnServiceListener != null){
        mOnServiceListener.onDataReceived("your data");
    }


来源:https://stackoverflow.com/questions/23282367/best-practice-for-pass-info-from-service-to-activity-or-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!