简体   繁体   English

Android推送通知服务

[英]Android Push Notification Service

Currently I have a Spring backend and I got a websocket on my android app which is listening for changes. 目前,我有一个Spring后端,并且我的android应用上有一个websocket,正在监听更改。 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). 阅读一些文章后,我发现可以由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 ? 即使应用未运行,如何保持WebSocket连接?

If Services are the solution - how can I pass the WebSocket instance from Activity to Service ? 如果服务是解决方案,如何将WebSocket实例从Activity传递给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. 因为Google限制了Android O的后台执行。

You can handle sockets in onStartCommand method: 您可以在onStartCommand方法中处理套接字:

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. 但是我认为FCM是推送消息的更好选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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