Android - Create a background service to receive PubNub messages

。_饼干妹妹 提交于 2019-12-10 11:06:48

问题


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 Subscribe Code

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();
            }
        });


    }

回答1:


Use your code inside a Service. A service is a background running task.

For more details, check this URL:-

Running a Background Service in Android




回答2:


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.



来源:https://stackoverflow.com/questions/29483671/android-create-a-background-service-to-receive-pubnub-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!