gpt4 book ai didi

java - 自定义监听器

转载 作者:行者123 更新时间:2023-12-02 05:06:16 28 4
gpt4 key购买 nike

我正在开发一个聊天应用程序。目前,当我打开 ChatActvity 时,我确实喜欢这样,所有套接字都已注册并且聊天正常...现在我想更改编码结构..我想在类中打开套接字,而不是在 Activity 类中,我需要向该类添加一个监听器。我如何实现这个..?

private class Chatroom {
private static void initialise() {
// Initialising the sockets and registering listeners to each socket
}
}

当 Chatroom 类中的套接字监听器被调用时,我想在我的 Activity 类中发出通知。

最佳答案

这可能是您需要的:

    public class RequestSender extends AsyncTask<String, Void, String> {

private final static String serverIP = "192.168.1.1";
private final static Integer serverPort = 1234;
private ServerResponseListener listener = null;

public void setServerResponseListener(ServerResponseListener listener){
this.listener=listener;
}

public interface ServerResponseListener {
public void onResponseReceive(String response);
}


@Override
protected String doInBackground(String... params) {
Socket socket = null;
try {
socket = new Socket(serverIP, serverPort);
} catch (IOException e) {
// return "server is unreachable" message or something
}

PrintWriter requestWriter = new PrintWriter(socket.getOutputStream());
BufferedReader resultReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String request = params[0] //for example
requestWriter.println(request);
requestWriter.flush();
String result = null;
while ((result = resultReader.readLine()) != null) {}
return result;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
listener.onResponseReceive(result);
}

}

这里是如何从 Activity 执行 AsynchTask 的示例:

public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestSender requestSender = new RequestSender();
requestSender.setServerResponseListener(new RequestSender.ServerResponseListener(){
@override
public void onResponseReceive(String response){
//
}
});
requestSender.execute("message");
}
}

阅读此内容:http://developer.android.com/reference/android/os/AsyncTask.html

关于java - 自定义监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27763734/

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