如何在具有多个活动的 android 应用程序上使用 Pusher?

How to use Pusher on an android app with multiple activities?

我们有这个 android 应用程序,我们在其中使用 Pusher 将实时更新从我们的服务器中继到 android 客户端。

问题是如果我们将以下代码片段添加到所有 activity 页面,Pusher 会为每个页面打开一个新的网络套接字。

如何与推送器建立一个连接并将其用于我们所有的活动?

String apiKey = "abcde";
        PusherOptions options = (new PusherOptions()).setEncrypted(false);
        Pusher ph = new Pusher(apiKey, options);
        ph.connect(new ConnectionEventListener() {
            @Override
            public void onConnectionStateChange(ConnectionStateChange change) {
                System.out.println("State changed to " + change.getCurrentState() +
                        " from " + change.getPreviousState());
            }

            @Override
            public void onError(String message, String code, Exception e) {
                System.out.println("There was a problem connecting!");
            }
        }, ConnectionState.ALL);

        if(pusher_channel != null){
            Channel channel = ph.subscribe(pusher_channel);

            // Bind to listen for events called "my-event" sent to "my-channel"
            channel.bind("user_is_typing", new SubscriptionEventListener() {
                @Override
                public void onEvent(String channel, String event, String data) {
                    //System.out.println("Received event with data: " + data);
                }
            });


        }

我们通过将连接脚本放在以下位置解决了这个问题:

public class MyApplication extends MultiDexApplication

现在我们的应用程序只打开一个 websocket。