Silvio Marijic
Silvio Marijic

Reputation: 481

Android reconnect internet issue

In my app i manage to determine is there connection or not, but i want that application itself try to reconnect 5 times, and every time to increase the interval between to reconnects m i did some code, but its not working, he give me response immediate.

Here is my reconnect class:

    public class ReestablishConnection {
    Application APP = new Application();
    boolean status;
    int reconnectInterval = 1000;
    int i;

    public boolean reconnect(String URL){
        Thread timer = new Thread(){
            public void run(){
                    for(i=1;i<6;i++){
                        if(APP.testConnection(APP.defaultUrl()) == 0){
                            status = false;
                        }else if(APP.testConnection(APP.defaultUrl()) == 1){
                            status = true;
                        }
                        try {
                            sleep(reconnectInterval * i);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }


            }
        };
        return status;
    }



}

Upvotes: 0

Views: 116

Answers (1)

Simon
Simon

Reputation: 14472

You create a new thread, which sleeps for a while, but the method which spawned it (reconnect) will return immediately. You should be using a Handler with postDelayed().

Take a look at the answer here:

How to run a Runnable thread in Android?

Sleep is used too often. The correct design is to implement a listener for when a connection is available and respond to listener callback in your UI.

Upvotes: 1

Related Questions