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

时间:2019-05-14 08:03:32

标签: java android sockets android-asynctask

我想通过Java套接字在android和服务器(在我的PC中)之间建立一些连接。简单来说,它只是通过局域网发送诸如字符串和整数之类的数据。

我阅读了有关AsyncTask类的信息。我在类(名为doInBackground()的类的RemoteClient方法中添加了套接字连接代码。这是通过套接字连接和初始化连接的代码:

    @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)方法。

谢谢..

1 个答案:

答案 0 :(得分:2)

是的,您只需将sendInteger放入AsyncTask中即可。我喜欢使用构造函数而不是AsyncTask参数,因为它更加灵活。您可以将接口实现为回调,以在UI中接收服务器答案。在执行onBackground之后,系统始终会调用onPostExecute。 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类,该类仅启动您的异步任务。然后,您始终可以将String作为JSON传递给AsyncTask。或者,您只使用AsyncTask,但随后我建议使用继承。

相关问题