简体   繁体   中英

Android Push Notification Service

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM