我们有这个 android 应用程序,我们使用 Pusher 将实时更新从我们的服务器中继到 android 客户端。
问题是,如果我们将以下代码片段添加到所有活动页面,Pusher 会为每个页面打开一个新的 Web 套接字。
如何与 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);
}
});
}