如何将数据从IntentService发送到Non-Activity类

时间:2015-06-11 11:31:04

标签: android android-service android-broadcast intentservice

我有两个服务类。一个是WebsocketService(extends Service)来管理Websocket related functionSocketMessageProcessing(extends IntentService)process response Received in WebSocketService。从Non-Activity(SocketImpl)班级,我成功地将数据发送到WebsocketService。但是我无法将回复发送回来自SocketImpl班级的SocketMessageProcessing班级。

//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?
    }

}

到目前为止我尝试过的事情。

  1. LocalBroadcastManager
    由于我希望在非活动课程中收到回复,因此我不知道如何管理registerunregister BroadcastReceiver

  2. 缓存SocketImpl对象并在SocketMessageProcessing中获取该对象并尝试调用onResponse()。但我确实得到"sending message to a handler on a dead thread"例外,所以认为这不是一个好主意。因为onResponse方法执行许多与UI相关的操作。

  3. 感谢任何帮助。提前谢谢!

1 个答案:

答案 0 :(得分:1)

您建议的选项#1是标准方式。而且您只需要一个上下文对象就可以注册和取消注册

LocalBroadcastManager.getInstance(context).registerReceiver(...

我刚刚在我的应用程序中尝试了非Activity类(使用它需要的活动上下文)并且它工作正常。

,我不确定你的意思
  

我不知道如何管理注册表并取消注册BroadcastReceiver