gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:39 25 4
gpt4 key购买 nike

我有两个服务类。一个是 WebsocketService(extends Service)管理Websocket related functionSocketMessageProcessing(extends IntentService)process response Received in WebSocketService .来自 Non-Activity(SocketImpl)类我能够成功地将数据发送到WebsocketService .但我无法将回复发送回 SocketImpl来自 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?
}

}

下面是我到目前为止尝试过的东西。

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

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

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

最佳答案

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

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

我刚刚在我的应用程序中从一个非 Activity 类(使用它无论如何都需要的 Activity 上下文)尝试了它并且它工作正常。不知道你说的是什么

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

关于android - 如何将数据从 IntentService 发送到 Non-Activity 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30779576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com