Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
999 views
in Technique[技术] by (71.8m points)

http - Android: Check network and real internet connectivity

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

public static boolean isNetworkAvailable(Context context) 
{
    ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

But having an active network interface doesn't guarantee that a particular networked service is available.

A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google

Common scenario:

  1. Android device connected to a Wi-Fi, which turns out to be a private network. So isNetworkAvailable will return that network is connected, but could not be connected to any other service
  2. Some times the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access Google/Yahoo.

One way is to check if "isNetworkAvailable" function returns TRUE, then run following code

HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);

   HttpEntity entity = response.getEntity();


     if (entity != null)
      {
         result = EntityUtils.toString(entity);
      }

   }
 catch (SocketException e)
  {
     return "Socket Exceptiopn:" + e.toString();
  }
 catch (Exception e)
  {
     return "General Execption:" + e.toString();
  }

But I think this is not an good way because it may consume lot of time

So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...