A Websocket connection is the ideal solution to your problem. This creates a persistent connection between the client and the server and both parties can start sending data at any time.
in OKHTTP you can implement this by
adding the library to your build gradle file compile 'com.squareup.okhttp3:okhttp:3.6.0'
Create a class that implements the okhttp WebsocketListener interface
private final class MyWebSocketListener extends WebSocketListener {
private static final int CLOSE_STATUS = 1000;
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("Hello");
webSocket.close(CLOSE_STATUS, "Goodbye");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
log(text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
log(bytes.hex());
}
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
webSocket.close(CLOSE_STATUS, null);
log("Closing");
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
log(t.getMessage());
}
}
Create a method to initiate the connection
private void connect() {
Request request = new Request.Builder().url("ws://my.websocket.url").build();
MyWebSocketListener listener = new MyWebSocketListener();
WebSocket ws = client.newWebSocket(request, listener);
\\ to shutdown the connection client.dispatcher().executorService().shutdown();
}
This should establish a connection with the server and should persist as long as the application is alive. I recommend reading more on websockets if you are the same person responsible for the backend.