How to check internet access on Android? InetAddress never times out

后端 未结 30 3454
猫巷女王i
猫巷女王i 2020-11-21 04:45

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

30条回答
  •  滥情空心
    2020-11-21 05:09

    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
    

提交回复
热议问题