4

I'm trying to show an animation in my app while connecting to a web server, just so that the user doesn't think that it's crashed/frozen.

Here's the bit in the code that may be relevant:

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.");
        }
    }
}

I think this might also be of use:

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();
}

The webSocketClient isn't actually defined in onCreate(), but the above method IS used in onCreate() anyway.

CiaranC94
  • 176
  • 4
  • 20

2 Answers2

2

First define a ProgressBar in your layout.xml and enable the indeterminate mode by using indeterminate parameter:

<ProgressBar  
     android:id="@+id/progressBar"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:visibility="invisible" 
     android:indeterminate = "true"/>

Then hide your progressBar as soon as the websocket connection has been established:

public void onCreate(){

    [...]

    mProgressBar     = (ProgressBar) findViewById(R.id.progressBar);

    mWebSocketClient = new WebSocketClient(uri) {

        @Override
        public void onOpen(ServerHandshake serverHandshake){
            this.progressBar.setVisibility(View.GONE); // or INVISIBLE
        }
        @Override
        public void onMessage(String s) {

        }

        @Override
        public void onClose(int i, String s, boolean b) {
        }
        @Override
        public void onError(Exception e) {
            this.progressBar.setVisibility(View.GONE); // or INVISIBLE
        }
    };

    mProgressBar.setVisibility(View.VISIBLE);
    mWebSocketClient.connect();
}

You can also define your ProgressBar as invisible and show it later before mWebSocketClient.connect() call.

P.S. I'm using this java websocket library in this example

dependencies {
    compile "org.java-websocket:Java-WebSocket:1.3.0"
}
alex
  • 8,904
  • 6
  • 49
  • 75
  • I only want it to show up while it's trying to connect the websocket. Should I define it as invisible in that case? – CiaranC94 May 06 '15 at 09:49
  • Should I do anything in onClose()? Also, why are you using this.progressBar? It won't work in my code. – CiaranC94 May 06 '15 at 11:27
  • Just for clarification, I've added my connectWebSocket() method, which is where the WebSocketClient is defined. – CiaranC94 May 06 '15 at 13:12
  • OK, I've just tried it out now. The progressBar doesn't show up unless I make it visible inside onOpen() rather than just before mWebSocketClient.connect(), but then again the layout file also have TextViews and ImageViews in it too, so they might be covering up the progressBar. – CiaranC94 May 06 '15 at 14:38
  • Sorry for taking a while to get back, but would using an AsyncTask help? – CiaranC94 May 13 '15 at 09:43
  • AsyncTask will not help. WebSocketClient allready use async connection. thats why you have `onOpen` or `onClose` methods. – alex May 13 '15 at 10:19
  • OK, thanks. The thing is that as soon as the fragment is opened, the progressBar shows up. I just want it to show up when sending data through the websocket. – CiaranC94 May 13 '15 at 10:23
  • @CiaranC94 what data do you mean? – alex May 13 '15 at 10:30
  • It's meant to send hashed alphanumeric tokens to a server. I'm an intern and I'm supposed to be developing an app for handling payments. – CiaranC94 May 13 '15 at 10:39
  • ok so let ProgressBar be hidden and make it visible if you user click a send button. Make it visible if you need it and hide if operation was completed – alex May 13 '15 at 10:54
  • Sorry, I should have been clearer. In the onMessage() method there's two things that can happen: confirmRegistration() or confirmTransaction(). That is when the message (i.e. the token) is sent to the server. EDIT: I've only just seen your message now. – CiaranC94 May 13 '15 at 10:58
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/77710/discussion-between-dit-and-ciaranc94). – alex May 13 '15 at 12:09
0

you can use j Progress bar in the program simultaneously with timer so it will be ok for the user to see the moving progress bar...if you want so reply me i will give you the coding of how to use the progress bar...