How to check Wifi is connected, but no Internet access in Android

后端 未结 4 1920
挽巷
挽巷 2020-12-28 19:35

I would like to know why wifi is connected but there is no internet access in Android. How can i check it? My code is:

ConnectivityManager cn=(ConnectivityMa         


        
相关标签:
4条回答
  • 2020-12-28 19:42

    You could try something like this:

    public void checkOnlineState() {
        ConnectivityManager CManager =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo NInfo = CManager.getActiveNetworkInfo();
        if (NInfo != null && NInfo.isConnectedOrConnecting()) {
            if (InetAddress.getByName("www.xy.com").isReachable(timeout))
            {  
             // host reachable  
            }
             else
             {    
             // host not reachable  
             }  
        }
        return;
    }
    

    dont forget the access

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

    Hope it will work :)

    0 讨论(0)
  • 2020-12-28 19:45

    In addition to what you are doing right now,you can use BroadcastReceiver for your application to get notified whenever the connectivity changes by registering <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> intent.

    Have a look at docs: BroadcastReceiver and Connectivity Monitoring for detailed description.

    I hope it will be helpful !

    0 讨论(0)
  • 2020-12-28 19:53
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                return true;
            }
            return false;
    
    0 讨论(0)
  • 2020-12-28 20:00

    Use this :

    public static boolean isInternetOn(Context context) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            // test for connection
            if (cm.getActiveNetworkInfo() != null
                    && cm.getActiveNetworkInfo().isAvailable()
                    && cm.getActiveNetworkInfo().isConnected()) {
                Log.v(TAG, "Internet is working");
                // txt_status.setText("Internet is working");
                return true;
            } else {
                // txt_status.setText("Internet Connection Not Present");
                Log.v(TAG, "Internet Connection Not Present");
                return false;
            }
        }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题