我们有这个android应用程序,我们在其中使用Pusher将实时更新从服务器中继到android客户端。
问题是,如果我们将以下代码段添加到所有活动页面,则Pusher为每个页面打开一个新的Web套接字。
如何与推杆建立一种连接并将其用于我们的所有活动?
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。