Android: Check network and real internet connectivity

前端 未结 3 1580
暖寄归人
暖寄归人 2020-12-12 00:51

Below is the piece of Android code which works fine to check if network is connected or not.

public static boolean isNetworkAvailable(Context context) 
{
            


        
3条回答
  •  抹茶落季
    2020-12-12 01:18

    check this code... it worked for me :)

    public static void isNetworkAvailable(final Handler handler, final int timeout) {
    
            // ask fo message '0' (not connected) or '1' (connected) on 'handler'
            // the answer must be send before before within the 'timeout' (in milliseconds)
    
            new Thread() {
    
                private boolean responded = false;
    
                @Override
                public void run() {
    
                    // set 'responded' to TRUE if is able to connect with google mobile (responds fast)
    
                    new Thread() {
    
                        @Override
                        public void run() {
                            HttpGet requestForTest = new HttpGet("http://m.google.com");
                            try {
                                new DefaultHttpClient().execute(requestForTest); // can last...
                                responded = true;
                            } catch (Exception e) {}
                        }
    
                    }.start();
    
                    try {
                        int waited = 0;
                        while(!responded && (waited < timeout)) {
                            sleep(100);
                            if(!responded ) { 
                                waited += 100;
                            }
                        }
                    } 
                    catch(InterruptedException e) {} // do nothing 
                    finally { 
                        if (!responded) { handler.sendEmptyMessage(0); } 
                        else { handler.sendEmptyMessage(1); }
                    }
    
                }
    
            }.start();
    
    }
    

    Then, I define the handler:

    Handler h = new Handler() {
    
        @Override
        public void handleMessage(Message msg) {
    
            if (msg.what != 1) { // code if not connected
    
            } else { // code if connected
    
            }
    
        }
    };
    

    and launch the test:

    isNetworkAvailable(h,2000); // get the answser within 2000 ms
    

    Code from Gilbou https://stackoverflow.com/a/5803489/2603719

    I hope i can Help you

提交回复
热议问题