我在 Android 中的私人频道订阅上遇到问题。这是我的代码
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", code);
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Accept", "application/json");
final HttpAuthorizer authorizer = new HttpAuthorizer("My URL");
authorizer.setHeaders(headers);
PusherOptions options = new PusherOptions()
.setEncrypted(true)
.setCluster("ap2")
.setAuthorizer(authorizer);
final Pusher pusher = new Pusher("KEY", options);
pusher.connect(new ConnectionEventListener() {
@Override
public void onConnectionStateChange(ConnectionStateChange change) {
}
@Override
public void onError(String message, String code, Exception e) { }
}, ConnectionState.ALL);
PrivateChannel channel = pusher.subscribePrivate(channelName);
channel.bind("message-sent", new PrivateChannelEventListener() {
@Override
public void onAuthenticationFailure(String string, Exception ex) {}
@Override
public void onSubscriptionSucceeded(String string) {
}
@Override
public void onEvent(String string, String string1, String string2) {}});
pusher.connect();
Run Code Online (Sandbox Code Playgroud)
这创建了成功的连接,但在订阅中它确实返回了任何结果。请帮我解决这个问题。
小智 3
我认为您的问题来自于在连接通道之前调用了 bind() 。
您可以尝试将订阅和绑定调用放入回调中,与此类似(我将它们移至方法中,以便更容易遵循):
Pusher pusher;
PrivateChannel channel;
void subscribeToChannel() {
channel = pusher.subscribePrivate(channelName, new PrivateChannelEventListener() {
@Override
public void onSubscriptionSucceeded(String s) {
bindToEvents();
}
@Override
public void onAuthenticationFailure(String s, Exception e) {}
@Override
public void onEvent(String s, String s1, String s2) {}
});
}
void bindToEvents() {
channel.bind("message-sent", new PrivateChannelEventListener() {
@Override
public void onAuthenticationFailure(String string, Exception ex) {}
@Override
public void onSubscriptionSucceeded(String string) {}
@Override
public void onEvent(String string, String string1, String string2) {}});
}
Run Code Online (Sandbox Code Playgroud)
在 main 方法中,您可以pusher.connect()调用subscribeToChannel()连接成功时将调用的方法:
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", code);
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Accept", "application/json");
final HttpAuthorizer authorizer = new HttpAuthorizer("My URL");
authorizer.setHeaders(headers);
PusherOptions options = new PusherOptions()
.setEncrypted(true)
.setCluster("ap2")
.setAuthorizer(authorizer);
final Pusher pusher = new Pusher("KEY", options);
pusher.connect(new ConnectionEventListener() {
@Override
public void onConnectionStateChange(ConnectionStateChange change) {
if (change.getCurrentState() == ConnectionState.CONNECTED) {
subscribeToChannel();
}
}
@Override
public void onError(String s, String s1, Exception e) {}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2284 次 |
| 最近记录: |