Reputation: 55
Currently I have a Spring backend and I got a websocket on my android app which is listening for changes. If there are changes the new data is being added to my app layout. Now I want to notificate the user when there is a change but the app is not running.
After reading some articles I found out, that this could be done by GCM (FCM). But I dont want to change my backend just because of this. So my question(s) :
How can I maintain the WebSocket connection, even when the app is not running ?
If Services are the solution - how can I pass the WebSocket instance from Activity to Service ?
It would really help me out if someone could give me some ideas. Thanks for your help :)
Upvotes: 3
Views: 1563
Reputation: 723
If you want to implement a background running service you will need to create a foreground service. Because Google limited the background execution on Android O.
You can handle sockets in onStartCommand method:
public class SocketService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
WebSocketClient client = new WebSocketClient(new URI("http://myserver.hu")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
}
@Override
public void onMessage(String message) {
}
@Override
public void onClose(int code, String reason, boolean remote) {
}
@Override
public void onError(Exception ex) {
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
return START_STICKY;
}
}
But I think the FCM is better choice for push messaging.
Upvotes: 1