Question

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!

Was it helpful?

Solution

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");
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top