java - 如何在AsyncTask类中添加更多方法?

标签 java android sockets android-asynctask

我想通过 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/

相关文章:

java - 在 java 中直接从 URL 将文件 POST 到 REST api,而不写入磁盘

java - 无法为类型为 org.springframework.boot.gradle.dsl.SpringBootExtension 的对象设置未知属性 'mainClass'

Android 模拟器 :/dev/kvm not found, 支持 Vt-x

c# - 创建一个套接字,移动客户端可以监听该套接字以获取通知

java - Equals 方法中浮点/ double 实例变量的相等比较是否应该准确?

java - 可以在 Windows 上的单元测试中运行的虚拟迷你 Linux 发行版

android - 将 Backendless API 与 Qt for Android 结合使用

android - 如何使用右侧的默认展开/折叠图标指示器制作可展开 ListView ?

objective-c - MAC OS X 上的客户端得到空响应(使用 BSD 套接字和 Cocoa 的 NSFileHandle)

java - 聊天程序: Client to Server Connectivity Issue