简体   繁体   中英

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



}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM