0

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



}
Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
Silvio Marijic
  • 483
  • 4
  • 12
  • 22

1 Answers1

1

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.

Community
  • 1
  • 1
Simon
  • 14,407
  • 8
  • 46
  • 61