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

How to send data from IntentService to Non-Activity class

我有两个服务class。一个是 WebsocketService(extends Service) 管理 Websocket related functionSocketMessageProcessing(extends IntentService) 管理 process response Received in WebSocketService。从 Non-Activity(SocketImpl) class 我可以成功地将数据发送到 WebsocketService。但是我无法将响应从 SocketMessageProcessing class.

发送回 SocketImpl 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?
    }

}

以下是我迄今为止尝试过的东西。

  1. LocalBroadcastManager
    因为我想在非 Activity class 中收到响应,所以我不知道如何管理 registerunregister BroadcastReceiver.

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

感谢任何帮助。提前致谢!

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

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

我刚刚在我的应用程序中从非 Activity class(使用它无论如何都需要的 activity 上下文)尝试了它并且它工作正常。我不确定

是什么意思

I don’t know how to manage the register and unregister the BroadcastReceiver