Android - 创建后台服务以接收PubNub消息 [英] Android - Create a background service to receive PubNub messages

查看:491
本文介绍了Android - 创建后台服务以接收PubNub消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PubNub API来获取实时消息。我已经实现了代码来订阅我的频道并接收正在进行的消息。即使我的应用程序未打开,我也希望这些消息在后台接收。我已经在android中了解了服务和广播接收器,但我不了解如何在PubNub中使用它。有没有正确的方法来实现这个目标?

I am using PubNub API to get real time messages. I have implemented code to subscribe to my channel and receive ongoing messages. I just want these messages to receive in background even if my application is not open. I have learned about services and broadcast receiver in android but I am not understanding the how to use this with PubNub. Is there any proper way to achieve this?

PubNub订阅代码

public static final String GLOBAL_CHANNEL = "NAME_OF_MY_CHANNEL";

public void subscribe() {

        Callback callback = new Callback() {
            @Override
            public void connectCallback(String channel, Object message) {
                notifyUser("Subscribed to location updates");
            }

            @Override
            public void disconnectCallback(String channel, Object message) {
                notifyUser("Unsubscribed to location updates");
            }

            public void reconnectCallback(String channel, Object message) {
                notifyUser("Resubscribed to location updates");
            }

            @Override
            public void successCallback(String channel, final Object message) {


                notifyUser(message.toString());


            }

            @Override
            public void errorCallback(String channel, PubnubError error) {
                notifyUser("Check your internet connection...!");
            }
        };

        try {
            pubnub.subscribe(GLOBAL_CHANNEL, callback);
        } catch (PubnubException e) {
            System.out.println(e.toString());
        }
    }

public void notifyUser(String message) {

        final String msg = (String) message;
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(context, msg, 0).show();
            }
        });


    }


推荐答案

< h2> PubNub Android订阅启动

您可以使用 PubNub subscribe-a-boot示例应用开始使用。如果您对此有任何疑问,请联系support@pubnub.com。

PubNub Android Subscribe-at-Boot

You can use the PubNub subscribe-a-boot sample app to get started. Please contact support@pubnub.com if you have any further questions with implementing this.

这篇关于Android - 创建后台服务以接收PubNub消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆