我试图在连接到 Web 服务器时在我的应用程序中显示动画,以便用户不会认为它已崩溃/冻结。
这是代码中可能相关的部分:
private void waitForWebSocketConnect() {
long start = System.currentTimeMillis();
long end = start + 3*1000; // 3 seconds
while (!mWebSocketClient.isOpen()) {
try {
Thread.sleep(200);
if(System.currentTimeMillis() >= end){
throw new InterruptedException();
}
} catch (InterruptedException e) {
fatalError("WebSocket did not connect. Please try again.");
}
}
}
我认为这也可能有用:
private void connectWebSocket() {
final Activity faActivity = super.getActivity();
URI uri;
try {
String uriString;
if(isRegistering){
//uriString = "ws://app.touchtechpayments.com:80/reg";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/reg";
} else {
//uriString = "ws://app.touchtechpayments.com:80/trans";
uriString = "wss://ec2-52-16-13-241.eu-west-1.compute.amazonaws.com/trans";
}
Log.d("uriString", uriString);
uri = new URI(uriString);
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Opened");
}
@Override
public void onMessage(String s) {
Log.d("Websocket", "Received message " + s);
if(isRegistering) {
confirmRegistration(s);
} else {
confirmTransaction(s);
}
}
@Override
public void onClose(int i, String s, boolean b) {
Log.d("Websocket", "Closed " + s);
if(!allDone) {
if (triedTwice) {
final String printToast = "Error received: " + s + "\nPlease try again.";
faActivity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, printToast, Toast.LENGTH_LONG).show();
faActivity.getFragmentManager().popBackStack();
}
});
} else {
Log.d("Websocket", "Trying for second time.");
triedTwice = true;
if (lastInputToServer != null) {
setupSSL();
connectWebSocket();
waitForWebSocketConnect();
mWebSocketClient.send(lastInputToServer);
}
}
}
}
@Override
public void onError(Exception e) {
this.progressBar.setVisibility(View.GONE);
Log.d("Websocket", "Error " + e.getMessage());
}
};
setupSSL();
mProgressBar.setVisibility(View.VISIBLE);
mWebSocketClient.connect();
}
webSocketClient 实际上并没有在 onCreate() 中定义,但上面的方法仍然在 onCreate() 中使用。