Android: Check network and real internet connectivity

前端 未结 3 1571
暖寄归人
暖寄归人 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

    0 讨论(0)
  • 2020-12-12 01:19

    Issue #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.

    Issue #2:
    Sometimes the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access google/yahoo.

    I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.
    

    Ultimately, you will need to Monitor the change in Network connection,

    Step 1:

    Just register a BroadcastReceiver for following action

    <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

    Step 2:

    when you get callback on onReceive(Context context,Intent intent) method ,check for connectivity status.

    i.e: boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);

    //apart from EXTRA_NO_CONNECTIVITY, there are other parameters also which will be useful to monitor

    Reference:

    Examples:

    Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android

    Android-getting-notified-of-connectivity-changes

    Github: Example for network-detect-notify

    Android Docs:

    Connectivity Monitoring

    Connectivity Manager

    I hope it will be helpful !!

    0 讨论(0)
  • 2020-12-12 01:26

    Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.

            boolean flag=false;
            ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null)
            {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i < info.length; i++)
                        if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        {
                            flag=true;
    
                        }
    
            }
            if(flag==true)
            {
                 Log.e("TAG","Internet Is Connected");
            }
            else
            {
                  Log.e("TAG","Internet Is Not Connected");
            }
    
    0 讨论(0)
提交回复
热议问题