Android - Create a background service to receive P

2019-05-26 06:02发布

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


    }

2条回答
聊天终结者
2楼-- · 2019-05-26 06:23

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

查看更多
老娘就宠你
3楼-- · 2019-05-26 06:31

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.

查看更多
登录 后发表回答