我想通过 Java 套接字在我的 android 和服务器(在我的 PC 中)之间建立一些连接。简单来说,它只是通过本地网络发送字符串和整数等数据。
我读到了有关 AsyncTask 类的内容。我在类(名为 RemoteClient
的类)中的 doInBackground()
方法中添加了套接字连接代码。以下是通过套接字进行连接和初始化连接的代码:
@Override
protected Void doInBackground(Void... arg0) {
Log.i("Socket","Connecting to the remote server: " + host);
try{
socket = new Socket(host,8025);
oos = new ObjectOutputStream(socket.getOutputStream());
}catch(IOException ex){
ex.printStackTrace();
}
return null;
}
我只是想通过套接字向服务器创建一个方法sendInteger(int value)
。我已经完成连接,连接良好。
那么,我应该把 sendInteger(int value)
方法放在哪里,我可以将该方法与实现的方法一起放在 RemoteClient
类中吗?
我想在单击按钮时调用 sendInteger(int value)
方法。
谢谢你..
最佳答案
是的,您可以将 sendInteger 放入 AsyncTask 中。我喜欢使用构造函数而不是 AsyncTask 参数,因为它更灵活。您可以将接口(interface)实现为回调,以在 UI 内接收服务器应答。 onPostExecute 总是在 onBackground 执行后立即被系统调用。 onPostExecute 也在 UI 线程上运行,因此您不必返回 UI 线程,因为您的 AsyncTask 将在不同的线程上运行。
您的代码将如下所示:
Fragmentclass or Activity:
private void onButtonClick() {
...
RemoteClient rc = new RemoteClient(value, (response) -> {
Log.d(response);
};
rc.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
...
}
public class RemoteClient extends AsyncTask<Void, Void, Void> {
private Callback callback;
private int intValue;
public RemoteClient(int intValue, Callback callback) {
this.callback = callback;
this.intValue = intValue;
}
@Override
protected Void doInBackground(Void... arg0) {
Log.i("Socket","Connecting to the remote server: " + host);
try{
socket = new Socket(host,8025);
oos = new ObjectOutputStream(socket.getOutputStream());
sendInteger(intvalue);
} catch(IOException ex){
ex.printStackTrace();
}
return null;
}
private void sendInteger(int value) {
// send the integer
}
protected void onPostExecute(Void aVoid) {
if (callback != null) {
callback.response;
}
}
private interface Callback {
void serverResponse(String value);
}
}
如果你想要更加灵活,你可以实现一个 NetworkManager 类,它只启动你的异步任务。然后,您始终可以将字符串作为 JSON 传递给 AsyncTask。或者您只使用 AsyncTask 但我建议使用继承。
关于java - 如何在AsyncTask类中添加更多方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56125654/