I have two Service class. one is WebsocketService(extends Service)
to manage Websocket related function
and SocketMessageProcessing(extends IntentService)
to process response Received in WebSocketService
. From Non-Activity(SocketImpl)
class I am successfully able to send data to WebsocketService
. But I am having trouble in sending response back to SocketImpl
class from SocketMessageProcessing
class.
//Common Class To send data to WebsocketService and Receive response from SocketMessageProcessing Service When Work Done. I am using this class as callback.
public class SocketImpl{
private String json;
private Context mContext;
private WebServiceResponseListener mListener;
public SocketImpl(Context context, String json, WebServiceResponseListener mListener){
//Initilize variables
}
public void execute() {
//Send request to websocket
WebSocketService.sendMessage(mAdapter.getContxet(), json);
}
public void onResponse(String resp, String tag) {
//Here I would like to receive response from IntenService Class.
}
}
//This class will perform Websocket related function and it will send response to SocketMessageProcessing once response received.
public class WebSocketService extends Service {
...
private void processResponse(String message){
Intent intent = new Intent(mContext, SocketMessageProcessing.class);
intent.putExtra("DATA", message);
mContext.startService(intent);
}
}
//Intent service to Process the incoming websocket response, And Send response Back to Class Where Its originate(SocketImpl).
public class SocketMessageProcessing extends IntentService{
@Override
protected void onHandleIntent(Intent intent) {
String json = intent.getStringExtra("DATA");
//Process json and send data back to class from where request originate?
}
}
Below things I have tried so far.
LocalBroadcastManager
As I want to receive response in Non-Activity class I don’t know how to manage theregister
andunregister
theBroadcastReceiver
.Cache
SocketImpl
Object and get that Object inSocketMessageProcessing
and tried callingonResponse()
. But I did get"sending message to a handler on a dead thread"
exception, So think it is not a good idea. because onResponse method perform many UI related operations.
Any help is appreciated. Thanks in advance!
Option #1 that you suggested is the standard way. And you just need a context object to be able to register and unregister
I've just tried that in my app from a non-Activity class (using an activity context which it needs anyway) and it works fine. I'm not sure what you mean by