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